FastAPI Basics • Lesson 14

Cookie Parameter Models

Group cookie parameters into Pydantic models for structured access to multiple cookies at once.

🎯 What You'll Learn

  • Group cookie parameters into Pydantic models
  • Apply validation and defaults to cookie groups
  • Understand when to use cookie models vs individual cookies
  • Handle optional cookie groups

Cookie Parameter Models

What You'll Learn

When your endpoint needs to read multiple cookies, declaring each one individually clutters your function signature. FastAPI 0.115+ lets you group related cookies into a Pydantic model, just like you can with query parameters.

By the end of this lesson, you'll understand how to:

  • Group cookie parameters into Pydantic models
  • Apply validation and defaults to cookie groups
  • Understand when to use cookie models vs individual cookies
  • Handle optional cookie groups

Cookies in HTTP

Cookies are small pieces of data stored in the browser and sent with every request to the same domain. Common uses include:

  • Session identifiers
  • User preferences (theme, language)
  • Tracking tokens
  • Feature flags

When a browser sends cookies, they appear in a single Cookie header:

Cookie: theme=dark; font_size=16; language=en

Individual Cookie Parameters

Before cookie models, you would declare each cookie separately:

from fastapi import FastAPI, Cookie

app = FastAPI()


@app.get("/preferences/")
def get_preferences(
    theme: str = Cookie(default="light"),
    font_size: int = Cookie(default=14),
    language: str = Cookie(default="en"),
):
    return {
        "theme": theme,
        "font_size": font_size,
        "language": language,
    }

This works but gets verbose with many cookies. The same parameter list must be repeated in every endpoint that reads these cookies.

Cookie Parameter Models

With FastAPI 0.115+, you can group cookies into a Pydantic model:

from fastapi import FastAPI, Cookie
from pydantic import BaseModel

app = FastAPI()


class UserPreferences(BaseModel):
    theme: str = "light"
    font_size: int = 14
    language: str = "en"


@app.get("/preferences/")
def get_preferences(prefs: UserPreferences = Cookie()):
    return {"preferences": prefs.model_dump()}

The Cookie() annotation tells FastAPI to read each model field from the request cookies instead of from the body or query string.

Key Concepts

Default Values

Every field in a cookie model should typically have a default value, because cookies may not be set yet. A user visiting your site for the first time will not have any cookies:

class UserPreferences(BaseModel):
    theme: str = "light"      # falls back to "light" if no cookie
    font_size: int = 14       # falls back to 14 if no cookie
    language: str = "en"      # falls back to "en" if no cookie

Validation

Because the model is a standard Pydantic model, you get full validation:

from pydantic import BaseModel, Field


class UserPreferences(BaseModel):
    theme: str = "light"
    font_size: int = Field(default=14, ge=8, le=32)
    language: str = "en"

If a cookie sends font_size=0, FastAPI returns a 422 error because the value violates the ge=8 constraint.

Reusability

Once you define a cookie model, you can reuse it across endpoints:

@app.get("/preferences/")
def get_preferences(prefs: UserPreferences = Cookie()):
    return {"preferences": prefs.model_dump()}


@app.get("/dashboard/")
def dashboard(prefs: UserPreferences = Cookie()):
    return {"layout": "dashboard", "theme": prefs.theme}

Forbidding Extra Cookies

You can optionally use model_config = {"extra": "forbid"} to reject requests with unexpected cookies, though this is less common for cookies than for query parameters since browsers often send cookies you did not set (e.g., analytics cookies).

When to Use Cookie Models

Use cookie models when:

  • Your endpoint reads three or more cookies
  • Multiple endpoints share the same set of cookies
  • You want to validate cookie values as a group

Use individual Cookie() parameters when:

  • You only need one or two cookies
  • The cookies are unrelated and do not form a logical group

Best Practices

  1. Always provide defaults for cookie fields since cookies may not exist
  2. Keep models focused -- group only related cookies together
  3. Add validation using Field() for numeric ranges or string patterns
  4. Reuse models across endpoints that need the same cookie data

What's Next?

You now know how to group cookies into Pydantic models. Next, you will learn how to do the same with HTTP headers using Header Parameter Models.

💡 Hint

Create a Pydantic model with cookie fields and annotate the parameter with Cookie().

Ready to Practice?

Now that you understand the theory, let's put it into practice with hands-on coding!

Start Interactive Lesson