How to Use Async Endpoint in FastAPI: Simple Guide
In FastAPI, you create an async endpoint by defining your path operation function with the
async def syntax. This allows FastAPI to handle requests asynchronously, improving performance for I/O-bound operations like database calls or network requests.Syntax
To create an async endpoint in FastAPI, define your function with async def and use the @app.get() or other HTTP method decorators. The async keyword tells Python to run this function asynchronously.
- @app.get("/path"): Decorator to define the route and HTTP method.
- async def function_name(): Defines an asynchronous function.
- return: Sends the response back to the client.
python
from fastapi import FastAPI app = FastAPI() @app.get("/async-endpoint") async def async_endpoint(): return {"message": "This is an async endpoint"}
Example
This example shows a simple async endpoint that waits asynchronously for 1 second before responding. It demonstrates how to use asyncio.sleep() inside an async FastAPI endpoint.
python
import asyncio from fastapi import FastAPI app = FastAPI() @app.get("/wait") async def wait_endpoint(): await asyncio.sleep(1) # Simulate async I/O operation return {"message": "Waited 1 second asynchronously"}
Output
{"message": "Waited 1 second asynchronously"}
Common Pitfalls
Common mistakes when using async endpoints in FastAPI include:
- Defining the endpoint function without
asyncwhen you want asynchronous behavior. - Calling blocking code (like time.sleep) inside async functions, which blocks the event loop.
- Not using
awaitwith async calls inside the endpoint.
Always use async def and await for asynchronous operations to keep FastAPI efficient.
python
from fastapi import FastAPI import time import asyncio app = FastAPI() # Wrong: blocking call inside async function @app.get("/bad") async def bad_endpoint(): time.sleep(1) # Blocks event loop, bad for async return {"message": "Blocked for 1 second"} # Right: use await with asyncio.sleep @app.get("/good") async def good_endpoint(): await asyncio.sleep(1) # Non-blocking sleep return {"message": "Waited 1 second asynchronously"}
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Define async endpoint | Use async def to create async function | async def my_endpoint(): |
| Use await | Await async operations inside endpoint | await asyncio.sleep(1) |
| Avoid blocking calls | Do not use time.sleep or other blocking code | Use asyncio.sleep instead of time.sleep |
| Route decorator | Use @app.get/post/put to define route | @app.get("/path") |
Key Takeaways
Use async def to define asynchronous endpoints in FastAPI.
Always await asynchronous operations inside async endpoints.
Avoid blocking calls like time.sleep inside async functions.
Async endpoints improve performance for I/O-bound tasks.
Use FastAPI decorators like @app.get to define routes.