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 fastapipip 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)
- 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.
0 comments:
Post a Comment