Field Rules: Lengths, Ranges and Choices

Field() puts rules on a model's fields, such as a name of 1 to 80 characters and an age of 18 or over, Literal allows only a fixed set of values, EmailStr checks the shape of an email address, and Query puts the same kind of rules on a query parameter.

Journeyman · FastAPI · Python · Updated

By

After this lesson you can

  • Add rules to a model's fields with Field, such as min_length, max_length, gt and le
  • Allow only a fixed set of values with Literal, check an email with EmailStr, and add rules to a query parameter with Query

Key takeaways

  • Field(min_length=1, max_length=80) limits how long text may be, and ge, gt, le and lt limit a number.
  • Literal lists the only values a field may hold, such as "dog", "cat" or "rabbit", matched exactly, capital letters included.
  • EmailStr checks that text has the shape of an email address, with an @ and a domain, but not that the mailbox exists.
  • A list default in a model is a fresh list for every model, and Field(default_factory=list) says so out loud.
  • Query puts the same rules on a query parameter, such as a limit between 1 and 50.

A type says what kind of value a field holds, but not whether the value makes sense. Every real form has rules: a username of 3 to 20 characters, a quantity of at least 1, a T-shirt size of S, M or L. This lesson puts Happy Tails' rules into the application model, so a bad application gets a 422 that names every broken rule, and your route never sees it.

A type isn't a rule

Request Models with Pydantic ended with a model that lets this body through, once it has an email:

{"name": "", "email": "rosa.example.com", "age": 15, "pet_name": "Clover", "pet_type": "dragon"}

Every value has the right type, and every value is wrong. Happy Tails' rules are a name of 1 to 80 characters, an adult applicant (18 or over), one of the pets the center has (a dog, a cat or a rabbit), and an email address that looks like one. Each rule goes on its field.

Lengths and ranges with Field

Field goes where a field's default would go, and holds its rules:

from pydantic import BaseModel, Field


class Application(BaseModel):
    name: str = Field(min_length=1, max_length=80)
    age: int = Field(ge=18, le=120)
    pet_name: str = Field(min_length=1, max_length=40)

min_length and max_length count the characters in text, so min_length=1 refuses the empty name. For numbers, the four rules are named after comparisons:

Rule Read it as age with this rule lets in
ge=18 greater than or equal to 18 18, 19, 20 …
gt=18 greater than 18 19, 20 … but not 18
le=120 less than or equal to 120 … 119, 120
lt=120 less than 120 … 119, but not 120

The difference between ge and gt is the edge: an 18-year-old may adopt, so the rule is ge=18. A Field with rules and no default is still required. To give a field rules and a default, name both: Field(default=1, ge=1).

Choices with Literal, emails with EmailStr

Two more kinds of rule come as types instead of Field rules. Here's the whole model with every rule in place:

from typing import Literal

from pydantic import BaseModel, EmailStr, Field


class Application(BaseModel):
    name: str = Field(min_length=1, max_length=80)
    email: EmailStr
    age: int = Field(ge=18, le=120)
    pet_name: str = Field(min_length=1, max_length=40)
    pet_type: Literal["dog", "cat", "rabbit"]
    has_yard: bool = False
    phone: str | None = None

Literal["dog", "cat", "rabbit"] (from Python's typing module, read "literally dog, cat or rabbit") lists the only values the field may hold. They're matched exactly, so "Rabbit" with a capital R is refused. EmailStr (from Pydantic) checks that the text has the shape of an email address: an @, and a domain after it. It needs the email-validator package, which fastapi[standard] installs. It can't tell whether the mailbox exists; only sending an email can.

The route from Request Models with Pydantic doesn't change at all. Send the bad body, and the answer is 422, with all four broken rules:

{"detail":[{"type":"string_too_short","loc":["body","name"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}},{"type":"value_error","loc":["body","email"],"msg":"value is not a valid email address: An email address must have an @-sign.","input":"rosa.example.com","ctx":{"reason":"An email address must have an @-sign."}},{"type":"greater_than_equal","loc":["body","age"],"msg":"Input should be greater than or equal to 18","input":15,"ctx":{"ge":18}},{"type":"literal_error","loc":["body","pet_type"],"msg":"Input should be 'dog', 'cat' or 'rabbit'","input":"dragon","ctx":{"expected":"'dog', 'cat' or 'rabbit'"}}]}

Reading FastAPI's 422 Validation Errors reads this answer piece by piece.

Fresh lists, and rules on query parameters

A list field can default to an empty list. In a plain Python function, a [] default is made once and shared by every call, a well-known trap. A model doesn't share it: Pydantic gives each model its own copy.

from pydantic import BaseModel


class Visit(BaseModel):
    pet_name: str
    notes: list[str] = []


first = Visit(pet_name="Biscuit")
second = Visit(pet_name="Pepper")
first.notes.append("Wagged at everyone")
print(first.notes)
print(second.notes)
['Wagged at everyone']
[]

notes: list[str] = Field(default_factory=list) does the same and says it out loud: default_factory names a function that makes a new default each time.

Query parameters take rules too. Staff list applications ten at a time, and a page of zero, or of a million, makes no sense. Query holds the rules, the way Field does, and Annotated (from typing, read "an int, with these rules attached") ties them to the type:

@app.get("/applications")
def list_applications(limit: Annotated[int, Query(ge=1, le=50)] = 10):
    return APPLICATIONS[:limit]

Query comes from fastapi, and Annotated from typing. GET /applications?limit=3 gives at most three applications, a request with no limit at most ten, and ?limit=0 answers 422 with the same kind of entry, pointing at the query string:

{"detail":[{"type":"greater_than_equal","loc":["query","limit"],"msg":"Input should be greater than or equal to 1","input":"0","ctx":{"ge":1}}]}

Check yourself

2 questions to try on the lesson page.

So what

With its rules written beside its fields, a model says everything an API will accept in one place, and FastAPI enforces every rule on every request, before your route runs.

Key terms

Related