How FastAPI Handles Requests
overview
In FastAPI, request processing is done inside the endpoint function. The request body and path parameters from the Pydantic model are passed as arguments to the endpoint function. These are used to retrieve data related to requests, generate responses, and so on.
Here, we will explain how to process requests with FastAPI using the following versions.
FastAPI v0.100.0
Python v3.11.4
uvicorn v0.22.0
Also, all the code created this time is GitHub is posted on
How to get request information
Use Pydantic models and dependency injection to get information about requests. Used by FastAPI endpoint functions to access data such as request headers, parameters, and body.
The sample code below is an example for understanding the request object in FastAPI. Receive a GET request, access the request headers, query parameters and body data and return a response containing those values.
main.py
from fastapi import FastAPI, Header, Depends, Body
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.post("/items/")
async def create_item(item: Item, user_agent: Optional[str] = Header(None)):
item_dict = item.dict()
item_dict.update({"user_agent": user_agent})
return item_dict
Commentary
- Import required libraries and modules:
from fastapi import FastAPI, Header, Depends, Body
from typing import Optional
from pydantic import BaseModel
FastAPI
is the main class for creating APIs. Header
is a function to get information from the request header, Depends
is a function to manage dependencies, and Body
is a function to get information from the request body. Optional
is part of a type hint that indicates that a value is optional (can be None
). BaseModel
is part of the Pydantic library, responsible for input data validation, serialization and documentation generation.
- Instantiate FastAPI application:
app = FastAPI()
app
creates a new instance of this FastAPI application. This is the main entry point for your application, where you configure things like routing definitions.
- Defining the
Item
model:
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
The Item
class inherits from Pydantics
BaseModel. This allows for data validation and serialization features. Here we define four fields:
name,
description,
priceand
tax`.
- Define routes and endpoints:
The example below defines an endpoint that creates a new item.
@app.post("/items/")
async def create_item(item: Item, user_agent: Optional[str] = Header(None)):
item_dict = item.dict()
item_dict.update({"user_agent": user_agent})
return item_dict
This endpoint is defined using FastAPI’s decorator feature, specifying an HTTP method (post
) and a URL path (/items/
). Also, the endpoint functions have the async
keyword to enable asynchronous processing.
The endpoint function receives two parameters. The first item: Item
retrieves data based on the Item
model from the request body and the second user_agent: Optional[str] = Header(None)
retrieves the user agent information from the request headers. to get
Inside the function, we first convert item
to a dictionary and then add user_agent
information. Finally, we return the updated dictionary as a response.
test
curl -X POST -H "Content-Type: application/json" -d '{"name": "item1", "price": 10.0}' http://localhost:8000/items/
summary
In this article, we have introduced in detail how to handle requests in FastAPI. I explained how to use the Pydantic model for endpoint function arguments and how to handle request bodies and path parameters. It also showed how to take advantage of dependency injection to access data such as request headers, parameters, and body.
Specifically, I created a FastAPI application and defined a Pydantic model named Item
within it. Then I created an endpoint to receive POST requests, and within that endpoint I got the Item
model data from the request body and the user agent information from the request headers. I have provided sample code to generate a response based on this information.
While FastAPI offers such advanced features, you’ll find it to be a very intuitive and easy-to-use framework. Through this article, you should have understood the basics of request processing using FastAPI and learned how to implement it in detail.