How to Use Async in FastAPI for Asynchronous Endpoints
In FastAPI, you use
async def to define asynchronous endpoint functions that allow non-blocking operations. This lets FastAPI handle many requests concurrently by awaiting asynchronous calls inside these functions.Syntax
Use async def to declare an asynchronous endpoint function in FastAPI. Inside this function, you can use await to pause execution until an asynchronous operation completes, such as database queries or HTTP calls.
This syntax tells FastAPI to run the function asynchronously, improving concurrency and responsiveness.
python
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): # Simulate async operation return {"item_id": item_id, "message": "This is an async endpoint"}
Example
This example shows a FastAPI app with an asynchronous endpoint that simulates a delay using asyncio.sleep. It demonstrates how to write async endpoints that do not block the server while waiting.
python
import asyncio from fastapi import FastAPI app = FastAPI() @app.get("/wait/{seconds}") async def wait_seconds(seconds: int): await asyncio.sleep(seconds) # Non-blocking wait return {"waited_seconds": seconds, "status": "done"}
Output
When you call /wait/3, the server waits 3 seconds asynchronously and then returns {"waited_seconds": 3, "status": "done"}
Common Pitfalls
One common mistake is mixing synchronous code inside async endpoints without using await, which blocks the event loop and reduces performance.
Another is defining endpoints with def instead of async def when you want asynchronous behavior.
python
from fastapi import FastAPI import time import asyncio app = FastAPI() # Wrong: blocking synchronous code inside async endpoint @app.get("/block") async def blocking_endpoint(): time.sleep(2) # Blocks event loop, bad practice return {"message": "This blocks the server"} # Right: use async sleep to avoid blocking @app.get("/nonblock") async def non_blocking_endpoint(): await asyncio.sleep(2) # Non-blocking return {"message": "This does not block the server"}
Quick Reference
- Use
async defto define asynchronous endpoints. - Use
awaitinside async functions to call async operations. - Avoid blocking calls like
time.sleep()inside async endpoints. - Async endpoints improve concurrency by not blocking the server during I/O waits.
Key Takeaways
Define FastAPI endpoints with async def to enable asynchronous behavior.
Use await inside async endpoints to call non-blocking operations.
Avoid synchronous blocking calls like time.sleep in async endpoints.
Async endpoints help FastAPI handle many requests concurrently.
Use async for I/O-bound tasks to improve app responsiveness.