Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Building Python Microservices with FastAPI

You're reading from   Building Python Microservices with FastAPI Build secure, scalable, and structured Python microservices from design concepts to infrastructure

Arrow left icon
Product type Paperback
Published in Aug 2022
Publisher Packt
ISBN-13 9781803245966
Length 420 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Sherwin John C. Tragura Sherwin John C. Tragura
Author Profile Icon Sherwin John C. Tragura
Sherwin John C. Tragura
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Part 1: Application-Related Architectural Concepts for FastAPI microservice development
2. Chapter 1: Setting Up FastAPI for Starters FREE CHAPTER 3. Chapter 2: Exploring the Core Features 4. Chapter 3: Investigating Dependency Injection 5. Chapter 4: Building the Microservice Application 6. Part 2: Data-Centric and Communication-Focused Microservices Concerns and Issues
7. Chapter 5: Connecting to a Relational Database 8. Chapter 6: Using a Non-Relational Database 9. Chapter 7: Securing the REST APIs 10. Chapter 8: Creating Coroutines, Events, and Message-Driven Transactions 11. Part 3: Infrastructure-Related Issues, Numerical and Symbolic Computations, and Testing Microservices
12. Chapter 9: Utilizing Other Advanced Features 13. Chapter 10: Solving Numerical, Symbolic, and Graphical Problems 14. Chapter 11: Adding Other Microservice Features 15. Index 16. Other Books You May Enjoy

Managing cookies

A cookie is a piece of information stored in the browser to pursue some purpose, such as login user authorization, web agent response generation, and session handling-related tasks. One cookie is always a key-value pair that are both string types.

FastAPI allows services to create cookies individually through the Response library class from its fastapi module. To use it, it needs to appear as the first local parameter of the service, but we do not let the application or client pass an argument to it. Using the dependency injection principle, the framework will provide the Response instance to the service and not the application. When the service has other parameters to declare, the additional declaration should happen right after the declaration of the Response parameter.

The Response object has a set_cookie() method that contains two required named parameters: the key, which sets the cookie name, and the value, which stores the cookie value. This method only generates one cookie and stores it in the browser afterward:

@app.post("/ch01/login/rememberme/create/")
def create_cookies(resp: Response, id: UUID, 
                   username: str = ''):
    resp.set_cookie(key="userkey", value=username)
    resp.set_cookie(key="identity", value=str(id))
    return {"message": "remember-me tokens created"}

The preceding create_cookies() method shows us the creation of remember-me tokens such as userkey and identity for the remember-me authorization of our online academic discussion forum project.

To retrieve these cookies, local parameters that have the same name as the cookies are declared in the service method as str types, since cookie values are always strings. As with Header and Form, the fastapi module also provides a Cookie function that is needed to initialize each declared cookie parameter variable. The Cookie() function should always have the None argument to set the parameters optionally, ensuring that the API method executes without problems whenever the headers are not present in the request transaction. The following access_cookie() service retrieves all the remember-me authorization cookies created by the previous service:

@app.get("/ch01/login/cookies")
def access_cookie(userkey: Optional[str] = Cookie(None), 
           identity: Optional[str] = Cookie(None)):
    cookies["userkey"] = userkey
    cookies["identity"] = identity
    return cookies
You have been reading a chapter from
Building Python Microservices with FastAPI
Published in: Aug 2022
Publisher: Packt
ISBN-13: 9781803245966
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image