- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - Middleware
A middleware is a function that is processed with every request (before being processed by any specific path operation) as well as with every response before returning it. This function takes each request that comes to your apppcation. It may perform some process with the request by running a code defined in it and then passes the request to be processed by the corresponding operation function. It can also process the response generated by the operation function before returning it.
Following are some of the middleware available in FastAPI pbrary −
CORSMiddleware
HTTPSRedirectMiddleware
TrustedHostMiddleware
GZipMiddleware
FastAPI provides app.add_middleware() function to handle server errors and custom exception handlers. In addition to the above integrated middleware, it is possible to define a custom middleware. The following example defines the addmiddleware() function and decorates it into a middleware by decorating it with @app.middleware() decorator
The function has two parameters, the HTTP request object, and the call_next() function that will send the API request to its corresponding path and return a response.
In addition to the middleware function, the apppcation also has two operation functions.
import time from fastapi import FastAPI, Request app = FastAPI() @app.middleware("http") async def addmiddleware(request: Request, call_next): print("Middleware works!") response = await call_next(request) return response @app.get("/") async def index(): return {"message":"Hello World"} @app.get("/{name}") async def hello(name:str): return {"message":"Hello "+name}
As the apppcation runs, for each request made by the browser, the middleware output (Middleware works!) will appear in the console log before the response output.
Advertisements