Book Image

Building Python Microservices with FastAPI

By : Sherwin John C. Tragura
3 (2)
Book Image

Building Python Microservices with FastAPI

3 (2)
By: Sherwin John C. Tragura

Overview of this book

FastAPI is an Asynchronous Server Gateway Interface (ASGI)-based framework that can help build modern, manageable, and fast microservices. Because of its asynchronous core platform, this ASGI-based framework provides the best option when it comes to performance, reliability, and scalability over the WSGI-based Django and Flask. When working with Python, Flask, and Django microservices, you’ll be able to put your knowledge to work with this practical guide to building seamlessly manageable and fast microservices. You’ll begin by understanding the background of FastAPI and learning how to install, configure, and use FastAPI to decompose business units. You’ll explore a unique and asynchronous REST API framework that can provide a better option when it comes to building microservices. After that, this book will guide you on how to apply and translate microservices design patterns in building various microservices applications and RESTful APIs using the FastAPI framework. By the end of this microservices book, you’ll be able to understand, build, deploy, test, and experiment with microservices and their components using the FastAPI framework.
Table of Contents (17 chapters)
1
Part 1: Application-Related Architectural Concepts for FastAPI microservice development
6
Part 2: Data-Centric and Communication-Focused Microservices Concerns and Issues
11
Part 3: Infrastructure-Related Issues, Numerical and Symbolic Computations, and Testing Microservices

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