from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello, World!"}?
from fastapi import FastAPI
app = FastAPI()
@app.get("/async_endpoint")
async def async_endpoint():
result = await some_async_function()
return {"result": result}?
from fastapi import Depends, FastAPI
app = FastAPI()
async def get_some_data():
# Asynchronous operations here
return {"data": "Some asynchronous data"}
@app.get("/")
async def read_data(data: dict = Depends(get_some_data)):
return data?
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks
):
message = f"message to {email}"
background_tasks.add_task(write_log, message)
return {"message": "Message sent in the background"}?
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
By embracing asynchronous programming, FastAPI is able to handle a large number of simultaneous connections efficiently, making it suitable for building scalable and performant web applications and APIs.