Pydantic model
- Python course
- Advanced
- Lesson 51/83
- 5 min
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 itemWith 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.
Practice 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).
Starter code
# bring in FastAPI from fastapi
# bring in BaseModel from pydantic
# bring in TestClient
# define app
# define Item model (name, price fields)
# add a post function at '/items/' (with item parameter)
# create a client with TestClient, send a post request with a structured-data bodySample 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)Expected output
{"name":"kalem","price":5.5}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Pydantic model concepts
| Term | Meaning |
|---|---|
BaseModel |
Model base class |
name: str |
Is a field definition |
item: Item |
Is a parameter type |
@app.post |
Defines a POST route |
2 What status code is returned when the body does not match the Pydantic model?
- 200
- 404
- 422 Correct answer
- 500
Explanation: A validation error returns a 422 status code.
3 Complete the BaseModel derivation
from pydantic import BaseModel
class Item(____):
name: str
price: float
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
Explanation: class Item(BaseModel) defines a model.