🍪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 adatetime
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 toTrue
, the cookie will only be sent over HTTPS connections, which provides better security.httponly
: If set toTrue
, 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 tocomment
, this parameter allows you to provide a URL with more information about the cookie.
Example programs
Program 1
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.
Last updated