Welcome back to another FastAPI course! In the previous course, you learned how to create a server, run it, and define GET
endpoints. Today, we are diving into handling asynchronous requests.
FastAPI is excellent for asynchronous tasks because it supports HTTP/2 and WebSockets. Asynchronous requests let your server handle multiple requests at once, making it more efficient, especially for tasks that take a long time like accessing a large database or an external service.
Using the async
keyword in your endpoint functions is crucial because it allows you to use the await
keyword for non-blocking operations. This means that while your server is waiting for the time-consuming operation to complete, it can handle other incoming requests, making the overall request handling more efficient.
Creating an asynchronous GET
endpoint in FastAPI is very easy! We just need to add the async
keyword before the function definition.
Here's what an asynchronous endpoint looks like:
Python1from fastapi import FastAPI 2import asyncio # Used to delay for 3 seconds 3 4app = FastAPI() 5 6# Mock database of crew members 7crew = [ 8 {"id": 1, "name": "Cosmo", "role": "Captain"}, 9 {"id": 2, "name": "Alice", "role": "Engineer"}, 10 {"id": 3, "name": "Bob", "role": "Scientist"} 11] 12 13 14# Asynchronous endpoint to retrieve all crew members 15@app.get("/crew/") 16async def get_all_crew_members(): 17 # Simulate a delay to mimic a time-consuming task 18 await asyncio.sleep(3) 19 return {"crew": crew}
In the above code, we're using the async
keyword before the function to declare it as an asynchronous function. While the await
keyword inside is used to call and wait for the asyncio.sleep(3)
function that simulates a time-consuming operation, like fetching data from a large database.
Note that the use of asyncio
library here is only for creating a delay. You do not need to import this to create an async endpoint.
And that's how you create an asynchronous endpoint using FastAPI. This knowledge is crucial when dealing with tasks that take some time to execute, as it allows everyone else to continue working while they wait!
In the next set of exercises, you'll practice handling asynchronous requests. Keep the concepts you've learned today fresh in your mind, and you'll do great! Happy coding!