DEV Community

Yegon Kipkirui Geoffrey
Yegon Kipkirui Geoffrey

Posted on • Edited on

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.

The key features are:

  • 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.

Middleware.

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.

  • 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.

Create a middleware

To create a middleware you use the decorator @app.middleware("http") on top of a function.

The middleware function receives:

  • The request.
  • A function call_next that will receive the request as a parameter.
    • This function will pass the request to the corresponding path operation.
    • Then it returns the response generated by the corresponding path operation.
  • You can then modify further the response before returning it.
     @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`
Enter fullscreen mode Exit fullscreen mode

Top comments (0)