Request body
Introduction to Request Body
When working with APIs, we often need to send data from a client to a server. One common way to do this is through the request body. In FastAPI, we use Pydantic models to define the structure of the request body.
Let's now dive into how we can use the request body in FastAPI.
Pydantic Models
Before we start working with the request body, we need to understand Pydantic models. A Pydantic model is a data structure that allows type checking, validation, serialization, and documentation. It helps us define the shape of our data and makes sure all data is valid according to the defined structure. Here's a simple example:
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
In this example, Item
is a Pydantic model with name
, description
, price
, and tax
fields. The types of the fields are defined right after the field name.
Using Request Body
To use the request body in FastAPI, we can define a Pydantic model as a parameter to our path operation function. FastAPI will automatically understand that the information should be taken from the request body.
Here is an example to illustrate:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_item(item: Item):
return item
In this example, create_item
function has a parameter item
of type Item
. When we send a POST request to /items/
, we need to include a request body matching the structure of the Item
model.
Request Body + Path Parameters
FastAPI is smart enough to distinguish between path parameters and the request body. You can declare both in your path operation function, like this:
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}
In this example, item_id
is a path parameter and item
is the request body. FastAPI will match the correct values to each parameter.
Request Body + Query Parameters
Just as with path parameters, FastAPI can also distinguish between query parameters and the request body:
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, q: str = None):
result = {"item_id": item_id, **item.dict()}
if q:
result.update({"query": q})
return result
In this example, q
is a query parameter and item
is the request body.
Recap
In FastAPI, we use Pydantic models to define the structure of our request body. We can then use these models as parameters in our path operation functions. FastAPI is smart enough to distinguish between the request body, path parameters, and query parameters.
In the next articles, we will explore more advanced FastAPI features. Stay tuned!
Remember to practice what you've learned here. The more you practice, the more comfort you'll gain working with the request body in FastAPI. Happy coding!