Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Integration with FastAPI

FastAPI Request Models with Pydantic

See how FastAPI uses Pydantic models to validate request bodies, query parameters and nested JSON, return 422 errors and generate OpenAPI documentation automatically.

FastAPI is built on Pydantic. When you declare a function parameter whose type is a Pydantic model, FastAPI reads the JSON body of the request, validates it with that model, and passes your function a finished, typed object. If validation fails, FastAPI answers with HTTP 422 and a list of errors before your code runs. The same model also produces the OpenAPI schema behind the interactive /docs page.

You already know the model half of this. This lesson is about the connection: what FastAPI does with each kind of parameter, and how to keep request models strict and safe.

FastAPI installs in the in-browser editor with micropip, and these examples call the app directly through httpx instead of starting a server, so you can read the real status codes and JSON. Two limits of the browser sandbox apply: endpoints are written as async def (plain def endpoints need threads, which the browser lacks), and there is no network server. On your machine you would write the same code and run fastapi dev; plain def endpoints work there too.

A request body model

Declare the body as a model-typed parameter. Each helper below, call, sends one request to the app and returns the response.

Python A POST endpoint with a request model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The loc of each error starts with "body", because FastAPI also validates path, query, header and cookie parameters, and tells you which part of the request was wrong. Your function body never ran for the invalid call.

sequenceDiagram
    participant C as Client
    participant F as FastAPI
    participant M as Pydantic model
    participant H as Your function
    C->>F: POST /items (JSON)
    F->>M: validate body
    alt valid
        M-->>F: ItemIn object
        F->>H: call with item
        H-->>C: 200 + JSON
    else invalid
        M-->>F: errors
        F-->>C: 422 + detail list
    end

Validation happens before your function is called.

Query parameters as a model

Since FastAPI 0.115 you can also group query parameters in a model with Query(). This is handy for filters and pagination that appear on many endpoints.

Python Query parameters in a model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

extra="forbid" is what turns the unknown color parameter into an error; without it FastAPI would silently ignore it. Repeated parameters (tags=a&tags=b) fill a list.

Nested bodies and several models

Nested models work as you would expect, and the error loc shows the full path. When a function takes several body parameters, FastAPI expects a JSON object with one key per parameter name. Use Body(embed=True) to wrap a single model the same way.

Python Nested models and error locations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The location ["body", "customer", "addresses", 1, "zip_code"] points at the exact missing field, which is what a front end needs to highlight the right input.

Keep request models strict

Request models are your public contract, so treat them carefully:

  • Use extra="forbid" so an unexpected key (an attempt to set is_admin, say) is an error, not silently dropped. This helps against mass assignment.
  • Use separate models for create, update and output: a client creating a user must not be able to set id or created_at.
  • Put limits on everything: max_length on strings, le on numbers, max_length on lists. Validation is also your first defense against huge payloads.
  • Use Field(examples=[...]) and description, which appear in the generated docs.
Python Create and update models

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

exclude_unset=True makes PATCH work: only the fields the client actually sent are applied, even if one of them was set to null on purpose.

The OpenAPI schema

Every model you declare is turned into JSON Schema and listed under components.schemas in /openapi.json. That is the data the /docs page shows. Constraints from Field become minLength, maximum, and so on, and examples appear as sample values.

Python Peeking at the generated schema

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

One declaration gives you validation, parsing, documentation and client code generation. Next you will control what the API returns: FastAPI Response Models.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does FastAPI return when a request body fails validation?

    FastAPI catches Pydantic's ValidationError and answers 422 with each error's location, type and message, before your function runs.
  2. 2. Why use extra="forbid" on a request model?

    Forbidding extras protects against mass assignment and catches typos in client code.
  3. 3. Which Pydantic call implements a PATCH that applies only the fields the client sent?

    exclude_unset=True leaves out fields that were not provided, so defaults do not overwrite stored data.
  4. 4. Where does FastAPI get the schema shown on /docs?

    Models become JSON Schema in components.schemas, and parameters become the operation description.

Summary

  • A model-typed parameter becomes the validated JSON body; invalid input gives 422 before your code runs.
  • Error loc begins with body, query, path or header and shows the exact nested path.
  • Annotated[Model, Query()] groups query parameters in a model.
  • Use extra="forbid", separate create/update/output models and limits on every field.
  • The same models generate the OpenAPI schema and /docs.

Next: FastAPI Response Models