FastAPI Basics • Lesson 11

Cookie Parameters

Learn to read and validate HTTP cookies in your FastAPI endpoints using the Cookie class.

🎯 What You'll Learn

  • Understand how cookies work in HTTP
  • Use FastAPI's Cookie class to read cookies
  • Handle optional cookies with default values
  • Validate cookie values with type annotations

Cookie Parameters

🎯 What You'll Learn

This lesson covers how to read and validate HTTP cookies in your FastAPI endpoints using the Cookie class. Cookies are a fundamental part of web development, used to store small pieces of data on the client side.

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

  • Read cookies from incoming HTTP requests
  • Use FastAPI's Cookie class for type-safe cookie access
  • Handle optional cookies with sensible default values
  • Validate cookie values using Python type annotations

📚 Theory

What Are Cookies?

HTTP cookies are small pieces of data that a server sends to a client's web browser. The browser stores them and sends them back with subsequent requests to the same server. Cookies are commonly used for:

  • Session management - Tracking user login sessions
  • User preferences - Remembering theme, language, or layout choices
  • Tracking - Recording user behavior across pages

How Cookies Work in HTTP

When a server wants to set a cookie, it includes a Set-Cookie header in its response:

Set-Cookie: session_id=abc123; Path=/; HttpOnly

The browser then sends that cookie back in subsequent requests via the Cookie header:

Cookie: session_id=abc123; theme=dark; language=en

FastAPI's Cookie Class

FastAPI provides a Cookie class that works similarly to Query and Path, but reads values from the Cookie header instead of the URL.

from fastapi import FastAPI, Cookie

app = FastAPI()

@app.get("/items/")
def read_items(session_id: str = Cookie()):
    return {"session_id": session_id}

Without Cookie(), FastAPI would interpret session_id as a query parameter. The Cookie() default tells FastAPI to look in the cookie header instead.

🔧 Key Concepts

Required vs Optional Cookies

A required cookie has no default value. If the cookie is missing, FastAPI returns a 422 validation error:

# Required cookie - must be present
session_id: str = Cookie()

An optional cookie provides a default value, so the endpoint works even when the cookie is absent:

# Optional cookie - defaults to "light" if missing
theme: str = Cookie(default="light")

# Optional cookie - defaults to None if missing
tracking_id: str | None = Cookie(default=None)

Type Conversion

FastAPI automatically converts cookie string values to the declared Python type:

# Cookie value "14" is automatically converted to int
font_size: int = Cookie(default=14)

# Cookie value "true" is automatically converted to bool
notifications: bool = Cookie(default=True)

If the conversion fails (e.g., a non-numeric string for an int cookie), FastAPI returns a 422 validation error with a clear error message.

Cookie vs Query vs Path

All three classes share the same interface but read from different parts of the request:

ClassSourceExample
QueryURL query string?session_id=abc123
PathURL path/users/abc123
CookieCookie headerCookie: session_id=abc123

Practical Example

Here is a complete example combining required and optional cookies:

from fastapi import FastAPI, Cookie

app = FastAPI()

@app.get("/user/settings/")
def get_user_settings(
    session_id: str = Cookie(),
    theme: str = Cookie(default="light"),
    language: str = Cookie(default="en"),
):
    return {
        "session_id": session_id,
        "theme": theme,
        "language": language,
    }

When called with the header Cookie: session_id=abc123; theme=dark; language=en, the endpoint returns:

{
    "session_id": "abc123",
    "theme": "dark",
    "language": "en"
}

🔗 What's Next?

In the next lesson, you'll learn about Header Parameters, where you'll discover how to read and validate HTTP headers using FastAPI's Header() class, including automatic hyphen-to-underscore conversion.

📖 Additional Resources

💡 Hint

Import Cookie from fastapi and use it as a parameter default: session_id: str | None = Cookie(default=None)

Ready to Practice?

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

Start Interactive Lesson