Python
Pydantic model
Learn request bodies with pydantic.BaseModel.
Pydantic model
FastAPI uses pydantic.BaseModel to validate the request body. You define a model class, give types to fields; FastAPI validates the body automatically and passes it to the function as a parameter.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return item
With the parameter item: Item, FastAPI turns the body into an Item instance. A bad body returns a 422 response.
Validation
The Pydantic model validates the body automatically. If a type does not match or a required field is missing, FastAPI returns a 422 status with a detailed error response.
# Item(name: str, price: float)
# Body: {"name": "kalem", "price": 5.5} -> validated
# Body: {"name": "kalem"} -> 422 (price missing)
On successful validation the function is called; the parameter is an Item instance with fields like item.name and item.price.
Exercise POST route with a Pydantic model
Start with from fastapi import FastAPI, from pydantic import BaseModel and from fastapi.testclient import TestClient. Define app = FastAPI(). Inside class Item(BaseModel): add fields name: str and price: float. With @app.post("/items/") define def create_item(item: Item): returning item. Create a client with client = TestClient(app). Define body = '{"name": "kalem", "price": 5.5}'. Make a POST request with resp = client.post("/items/", content=body.encode(), headers={"content-type": "application/json"}). Print the response with print(resp.text).
Show example solution
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.testclient import TestClient
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return item
client = TestClient(app)
body = '{"name": "kalem", "price": 5.5}'
resp = client.post("/items/", content=body.encode(), headers={"content-type": "application/json"})
print(resp.text)
Test yourself
-
Match the Pydantic model concepts
- BaseModel
- Model base class
- name: str
- Is a field definition
- item: Item
- Is a parameter type
- @app.post
- Defines a POST route
-
What status code is returned when the body does not match the Pydantic model?
Show answer
422 — A validation error returns a 422 status code.
-
Complete the BaseModel derivation
from pydantic import BaseModel
class Item(____):
name: str
price: float
Show answer
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
Next lesson: Path parameter