Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 72 ยท REST APIs

Validation and Serialization

Validate incoming JSON and shape outgoing JSON in Flask. Learn schemas with Pydantic, clear 422 error responses, partial updates and hiding private fields.

Everything a client sends is untrusted. A field may be missing, a number may arrive as a string, an email may be nonsense, and an attacker may add fields you never asked for. Checking each of these by hand with if statements works for two fields and becomes unreadable at twenty. The reverse direction has a problem too: when you send data back, you must pick exactly the fields to expose and turn Python objects into plain JSON types.

A schema solves both directions. You describe the data once, as a class, and a library does two jobs: validation (turn untrusted input into trusted, typed data, or a list of problems) and serialization (turn your objects into safe JSON). In this lesson you will use Pydantic, which installs in the browser with micropip like Flask itself, and see where Marshmallow, the other popular choice, fits.

The pipeline

flowchart LR
    J["request JSON"] --> V{"schema<br/>validates"}
    V -->|invalid| E["422 + list of errors"]
    V -->|valid| O["typed object"]
    O --> L["your logic / database"]
    L --> S["schema picks<br/>public fields"]
    S --> R["JSON response"]

Validation guards the way in; a response schema guards the way out.

What validation means, by hand

Before using a library, here is the job written out in plain Python. It checks types, applies limits and collects all the problems, not just the first. The aim is to see what the library will do for us.

Python Hand-written validation

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.

It works, but every new field costs several lines, the error messages are ad hoc, and nothing documents the shape of the data. Libraries fix all three.

Pydantic models

With Pydantic you declare fields with type hints. Constraints go in Field(...). Calling Model.model_validate(data) returns an instance or raises ValidationError. Pydantic also coerces compatible values by default: the string "36" becomes the integer 36 (in the default "lax" mode), and extra keys are ignored unless you forbid them.

Python A Pydantic model and its errors

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.

Read the output carefully:

  • " Ada " was stripped and "36" became 36 before your code ever sees it.
  • Each error has a loc (where) and a type (a stable machine-readable name such as missing, string_too_short or greater_than_equal). There is also a human msg.
  • extra="forbid" turned the unexpected admin key into an error. This is a cheap defence against mass assignment, where a client sneaks in a field such as is_admin.
  • Your own ValueError inside a validator becomes a normal validation error with the type value_error.

Connecting a schema to Flask

Write the glue once as a decorator, and every view stays tidy. The decorator reads the JSON body, validates it with a model, and either passes the typed object to the view or answers with a 422 that uses the shared error shape from Building JSON APIs.

Python A validate_body decorator

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.

Your view now receives body, a typed BookIn, and never sees raw, unchecked input. The same decorator works for every endpoint; only the model changes. Ready-made packages such as flask-pydantic do this for you, but the hand-rolled version is about fifteen lines and shows what is happening.

Serialization: choosing what goes out

Validation protects you from the client. Serialization protects the client (and you) from yourself. A database row often has fields that must never leave the server: password hashes, internal flags, other users' data. Use a separate output model that lists only the public fields, and build the response from that.

Pydantic's from_attributes=True lets an output model read from any object with matching attributes (an ORM row, a dataclass). model_dump(mode="json") converts values such as dates and UUIDs into JSON-safe strings.

For partial updates (PATCH), use model_dump(exclude_unset=True): it contains only the fields the client actually sent, so a missing field means "leave it alone" and an explicit null means "clear it".

Python Input model, output model and PATCH

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.

Notice that the output has no password_hash and no is_admin even though the row has both: the response model is an allow-list. The joined date was turned into the string "2024-03-09" by mode="json".

Marshmallow takes a different approach: a schema class lists field objects, and load() validates while dump() serializes. It has no type-hint magic, so it is explicit and works well when the schema should be separate from your classes. A sketch (read-only here; you install it with pip install marshmallow):

Python
from marshmallow import Schema, fields, validate, ValidationError

class BookSchema(Schema):
    title = fields.Str(required=True, validate=validate.Length(min=1, max=80))
    year = fields.Int(required=True, validate=validate.Range(min=1450, max=2100))

try:
    data = BookSchema().load(request.get_json())
except ValidationError as err:
    return {"error": {"code": "validation_failed", "details": err.messages}}, 422

err.messages is a dictionary such as {"year": ["Must be greater than or equal to 1450 and less than or equal to 2100."]}. Pydantic and Marshmallow are both good; choose Pydantic if you already like type hints (and plan to use FastAPI later), Marshmallow if you prefer explicit field objects or use flask-smorest / apispec.

Practical rules

  • Validate at the edge: every route that accepts a body, query parameters or form data.
  • Use separate models for input and output (and often for create vs update). One model for everything leaks fields.
  • Forbid unknown fields on input unless you have a reason not to.
  • Return all the errors at once with a field name and a stable code, so a form can highlight every wrong field in one round trip.
  • Validation checks shape. Business rules ("this email is already taken", "the stock is zero") still belong in your logic, returned as 409 or 422.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main reason to use separate input and output models?

    An output model is an allow-list of public fields, and an input model rejects fields a client should not set. One shared model tends to accept or leak too much.
  2. 2. What does ConfigDict(extra="forbid") do on an input model?

    Forbidding extras makes an unexpected key such as is_admin a validation error, which helps prevent mass assignment.
  3. 3. Which Pydantic call gives you only the fields the client actually sent in a PATCH body?

    exclude_unset=True leaves out fields that were never provided, so you update only those. A plain model_dump() would also include defaults, which would overwrite stored data.
  4. 4. Which status code is common for a request whose JSON is well-formed but has invalid field values?

    422 (or 400, if you prefer one code for all bad input) tells the client that the data was understood but failed validation.

Summary

  • A schema describes data once and does validation (input) and serialization (output).
  • Pydantic models use type hints plus Field constraints; model_validate returns a typed object or raises ValidationError, whose errors() give loc and type.
  • Wrap validation in a decorator so views receive trusted, typed data, and answer 422 with all the errors and one shared format.
  • Use extra="forbid" against mass assignment, separate output models to hide private fields, and exclude_unset=True for PATCH.
  • Marshmallow offers the same ideas with explicit field objects.
  • Validation checks the shape of data; business rules are still your job.

Next, decide who is calling your API with API Authentication with Tokens.