CS504070 - FastAPI Tutorials
  • 🧩CS504070 - FastAPI Tutorials
  • 🔎Unit 1: Python Type Hint
  • ⚙️Unit 2: Pydantic
  • 🔃Unit 3: Concurrency
  • 💾Unit 4: Install FastAPI
  • 🍉Unit 5: Hello World!
  • 🍌Unit 6: Path Parameters
  • 🍋Unit 7: Query Parameters
  • 🍊Unit 8: Request Body
  • 🍐Unit 9: Query Parameters and Validations
  • 🍎Unit 10: Path Parameters and Validations
  • 🍏Unit 11: Multiple Parameters
  • 🍇Unit 12: Request Body - List Fields and Nested Models
  • 🍓Unit 13: Data Types
  • 🍪Unit 14: Cookie Parameters
  • 🫐Unit 15: Header Parameters
  • 🍈Unit 16: Response Model - Return Type
  • 🍒Unit 17: Additional Models
  • 🥑Unit 18: Implementing JWT Authentication with FastAPI
  • ⚙️Appendix A
  • 🍭Appendix B
Powered by GitBook
On this page
  • Introduction
  • Common parameters
  • Example programs
  • Program 1
  • Program 2

Unit 14: Cookie Parameters

Introduction

In FastAPI, cookies can be managed and utilized for various purposes such as session management, user authentication, or storing user preferences. When working with cookies in FastAPI, you can use several parameters to customize their behavior.

Common parameters

  • key: This parameter specifies the name of the cookie.

  • value: This parameter sets the value of the cookie.

  • max_age: It defines the maximum age of the cookie in seconds. After this duration, the cookie will be considered expired. If not set, the cookie will be deleted when the user closes the browser (session cookie).

  • expires: This parameter specifies a specific expiration date and time for the cookie. It takes a datetime object. Once this datetime is reached, the cookie will be considered expired.

  • domain: It specifies the domain for which the cookie is valid. By default, the cookie is only valid for the domain that set it. You can set it to a broader domain to allow the cookie to be accessible across subdomains.

  • path: This parameter defines the URL path for which the cookie is valid. If not specified, the cookie will be valid for the entire domain.

  • secure: If set to True, the cookie will only be sent over HTTPS connections, which provides better security.

  • httponly: If set to True, the cookie will be accessible only through HTTP requests and not through client-side scripts like JavaScript. This can prevent certain types of attacks such as cross-site scripting (XSS).

  • samesite: This parameter protects against certain types of cross-site request forgery (CSRF) attacks by specifying when the browser should send the cookie in a cross-site request. Possible values are 'strict', 'lax', or 'none'.

  • comment: This parameter allows you to provide a human-readable comment about the cookie. It's mainly for documentation purposes.

  • comment_url: Similar to comment, this parameter allows you to provide a URL with more information about the cookie.

Example programs

Program 1

from fastapi import FastAPI, Cookie, Response
from datetime import datetime, timedelta, timezone

app = FastAPI()

@app.get("/set-cookie")
async def set_cookie(response: Response):
    response.set_cookie(
        key="fakesession",
        value="fake-cookie-session-value",
        expires=datetime.now().replace(tzinfo=timezone.utc) + timedelta(days=30),
        max_age=3600,
        domain="example.com",
        path="/",
        secure=True,
        httponly=True,
        samesite="strict")
    return {"message": "Cookie set successfully!"}

Fig. 1 shows the result when using Postman to test the program. You should switch to the Headers tab to view the value of set-cookie key.

Program 2

You can define Cookie parameters the same way you define Query and Path parameters.

from typing import Annotated
from fastapi import Cookie, FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(ads_id: Annotated[str | None, Cookie()] = None):
    return {"ads_id": ads_id}
PreviousUnit 13: Data TypesNextUnit 15: Header Parameters

Last updated 1 year ago

🍪
Fig. 1. View cookie value in Postman
Page cover image