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 API responses

The use of jsonable_encoder() can help an API method not only with data persistency problems but also with the integrity and correctness of its response. In the signup() service method, JSONResponse returns the encoded Tourist model instead of the original object to ensure that the client always received a JSON response. Aside from raising status codes and providing error messages, JSONResponse can also do some tricks in handling the API responses to the client. Although optional in many circumstances, applying the encoder method when generating responses is recommended to avoid runtime errors:

from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
@router.get("/ch02/destinations/details/{id}")
def check_tour_profile(id: UUID):
    tour_info_json = jsonable_encoder(tours[id])
    return JSONResponse(content=tour_info_json)

check_tour_profile() here uses JSONResponse to ensure...