StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Tuesday, June 1, 2021

Python FastAPI microservice before and after response handler

 June 01, 2021     Microservices, Python     No comments   

When developing microservices we run into situations where we need to do an action before and after handling the API path function. Examples include simple logging of requests, adding a custom value to the request or sending a custom header in responses etc. This article provides an example of how this can be achieved in Python based microservices.

In Python FastAPI is a modern, high performance framework to build microservices. Example below provides a simple microservice built with FastAPI which supports an API path "/hello" and returns a JSON response. 

To run this example need to install these modules.
pip install fastapi
pip install uvicorn
Here uvicorn is an implementation of ASGI (Asynchronous Service Gateway Interface) specifications and provides a standard interface between async-capable Python web servers, frameworks and applications.

FastAPI supports "middleware" which can be leveraged to write a function that works with every request before it is processed by any specific path operation. And also with every response before returning it. It takes each request that comes to your application. 
  • It can then do something to that request or run any needed code. 
  • Then it passes the request to be processed by the rest of the application (by some path operation). 
  • It then takes the response generated by the application (by some path operation). 
  • It can do something to that response or run any needed code. 
  • Then it returns the response.

from fastapi import FastAPI, Request
import uvicorn

app = FastAPI()


@app.get("/hello")
async def sayhello(request: Request):
    print("Custom request value: ", request.state.myval)
    return {"message": "Hello World"}


@app.middleware("http")
async def service_handler(request: Request, call_next):
    print("In service handler ..")
    print(request.headers)
    print(request.query_params)

    # Add custom value to the request
    request.state.myval = 10

    # Perform the action
    response = await call_next(request)

    # Add custom header to the response
    response.headers["X-CUSTOM-HEADER1"] = "MYVAL"
    return response

if __name__ == '__main__':
    uvicorn.run('SayHello:app',
                host='127.0.0.1',
                port=8089,
                reload=True)
To create a middleware we can use the decorator @app.middleware(“http”) on top of a function. Here service_handler is the function that receives: 
  • The request 
  • Prints the request details 
  • Adds a custom value to the request. request.state is a property of each Request object. It is there to store arbitrary objects to the request itself. 
  • Invokes call_next that will receive the request as a parameter 
  • Receives the response generated by the corresponding path operation 
  • Modify the response before returning by adding a custom header
If the API call is made from Postman we can observe the custom header added in response.



  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk