Pydantic Schemas for Request and Response
BaseModel, field validation, type hints, response_model, handling validation errors.
Pydantic Schemas for Request and Response is a free Learn AI with Python lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Schemas?
Raw dicts are error-prone. Pydantic models define the exact shape of requests and responses, validating types automatically and documenting your API. FastAPI uses them natively.
The BaseModel
Pydantic schemas subclass BaseModel. Each typed attribute becomes a validated field; wrong types are rejected before your code runs.
from pydantic import BaseModel
class PredictRequest(BaseModel):
features: list[float]A Request Schema
Define what clients must send. Here features must be a list of floats, and you can add more fields like a model version or request id.
class PredictRequest(BaseModel):
features: list[float]
model_version: str = "latest"A Response Schema
Define what your API returns so clients get a stable, documented contract.
class PredictResponse(BaseModel):
prediction: float
probability: floatUsing Schemas in an Endpoint
Type the parameter with your request model and FastAPI parses + validates the JSON body automatically into a typed object.
from fastapi import FastAPI
app = FastAPI()
@app.post("/predict")
def predict(req: PredictRequest):
pred = model.predict([req.features])[0]
return {"prediction": pred, "probability": 0.92}The response_model Parameter
Pass response_model to the route decorator. FastAPI validates and filters the output to match the schema, stripping any extra fields and documenting the response in /docs.
@app.post("/predict", response_model=PredictResponse)
def predict(req: PredictRequest) -> PredictResponse:
return PredictResponse(prediction=1.0, probability=0.92)list[float] for Feature Vectors
Typing features as list[float] means Pydantic rejects strings or mixed types before inference, catching malformed input at the boundary instead of deep inside model code.
HTTPException for Errors
When validation passes types but business rules fail (wrong number of features, unknown model), raise HTTPException with a status code and message.
from fastapi import HTTPException
@app.post("/predict")
def predict(req: PredictRequest):
if len(req.features) != 4:
raise HTTPException(status_code=422,
detail="Expected exactly 4 features")
return {"prediction": model.predict([req.features])[0]}Field Validators
A field_validator enforces custom rules on a field, like rejecting empty feature lists, before the endpoint logic even runs.
from pydantic import BaseModel, field_validator
class PredictRequest(BaseModel):
features: list[float]
@field_validator("features")
@classmethod
def not_empty(cls, v):
if not v:
raise ValueError("features cannot be empty")
return vField Constraints
Use Field for declarative constraints like minimum length or numeric ranges, which also appear in the auto-generated docs.
from pydantic import BaseModel, Field
class PredictRequest(BaseModel):
features: list[float] = Field(min_length=1)Automatic 422 Responses
When a request fails Pydantic validation, FastAPI automatically returns a 422 Unprocessable Entity with a detailed error body, no extra code needed. This is one of FastAPI biggest productivity wins.
Quick Check
Test your Pydantic schema knowledge.
Recap
You defined BaseModel schemas for requests and responses, used list[float] for features, applied response_model, raised HTTPException for business errors, and added field validators. FastAPI auto-returns 422 on invalid input. Next: loading and serving the model.
Frequently asked questions
Is the “Pydantic Schemas for Request and Response” lesson free?
Yes — the full text of “Pydantic Schemas for Request and Response” is free to read here on the web, and the Learn AI with Python course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.
What will I learn in “Pydantic Schemas for Request and Response”?
BaseModel, field validation, type hints, response_model, handling validation errors. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn AI with Python?
No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Pydantic Schemas for Request and Response” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn AI with Python lesson?
Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- FastAPI Basics for ML Engineers
- Pydantic Schemas for Request and Response
- Loading and Serving ML Models
- Dockerizing the Model API