21
Middleware in fastAPI
According to official documentation, FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
Fast to code: Increase the speed to develop features by about 200% to 300%. *
Fewer bugs: Reduce about 40% of human (developer) induced errors. *
Intuitive: Great editor support. Completion everywhere. Less time debugging.
Easy: Designed to be easy to use and learn. Less time reading docs.
Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
Robust: Get production-ready code. With automatic interactive documentation.
Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
A "middleware" is a function that works with every request before it is processed by any specific path operation. And also with every response before returning it.
To create a middleware you use the decorator @app.middleware("http") on top of a function.
The middleware function receives:
- This function will pass the request to the corresponding path operation.
- Then it returns the response generated by the corresponding path operation.
@app.middleware("http")
async def log_requests(request: Request, call_next):
idem = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
logger.info(f"rid={idem} start request path={request.url.path}")
start_time = time.time()
response = await call_next(request)
process_time = (time.time() - start_time) * 1000
formatted_process_time = '{0:.2f}'.format(process_time)
logger.info(f"rid={idem} completed_in={formatted_process_time}ms status_code={response.status_code}")
return response`
21