Introducción a FastAPI
FastAPI: La herramienta definitiva para el desarrollo web
¿Qué es y por qué usar FastAPI?
Instalación y configuración de FastAPI
Parámetros y Validación
Parámetros de ruta y consultas en FastAPI
¿Cómo validar datos en FastAPI con Pydantic?
Modelado de Datos en APIs con FastAPI
Validación y Gestión de Modelos en FastAPI
CRUD en FastAPI
¿Cómo conectar FastAPI a una base de datos usando SQLModel?
Creación y consulta de registros en SQLite con SQLModel y FastAPI
Crear un CRUD básico en FastAPI: Eliminar
Crear un CRUD básico en FastAPI: Actualizar
Arquitectura en FastAPI
Arquitectura de APIs escalables en FastAPI
Bases de Datos y Consultas
¿Cómo gestionar datos relacionados en SQLModel con FastAPI?
¿Cómo crear relaciones de muchos a muchos en SQLModel?
Relacionar Modelos de Datos en FastAPI: Implementación de Relaciones
Consultas avanzadas con SQLModel en FastAPI
Implementación de validación de datos en FastAPI con Pydantic
Middlewares
¿Cómo implementar paginación de datos en FastAPI?
Implementación y Uso de Middlewares en FastAPI
Unit Testing
Pruebas Unitarias en FastAPI: Configuración con Pytest y SQLAlchemy
¿Cómo implementar pruebas automáticas en endpoints de FastAPI?
Seguridad y Autenticación
Autenticación de API en FastAPI con HTTPBasicCredentials
Siguientes pasos en FastAPI
You don't have access to this class
Keep learning! Join and start boosting your career
Middlewares in FastAPI are fundamental tools for modifying the behavior of requests in a centralized and efficient way. A middleware, in simple terms, is a function that runs before and after each request, allowing to intercept and extend the base functionality of an API without modifying each endpoint individually.
A middleware captures each incoming request, processes some functionality, and then allows the flow to continue to the corresponding endpoint. FastAPI offers several predefined middlewares for common cases, but also allows you to create custom middlewares for specific needs.
To create a custom middleware, we can define an asynchronous function that records the processing time of each request. The steps are:
main.py
file, where the application is defined, add a new function log_request_time
.request
: The object that contains the request information.call_next
: A function that calls the next operation in the request chain.The goal is to record the time before and after executing the request, and then calculate how long the whole process took.
import timefrom fastapi import FastAPI, Request app = FastAPI()@app.middleware("http")async def log_request_time(request: Request, call_next):start_time = time.time() # Initial request timeresponse = await call_next(request) # Call request functionalityprocess_time = time.time() - start_time # Calculate total processing time # Print URL and processing time in secondsprint(f"Request {request.url} completed in {process_time:.2f} seconds") return response
To register the middleware, it is necessary to use app.middleware
and specify the type. In this case, we will use the http
type so that it is executed with all HTTP requests.
log_request_time
in the application with @app.middleware("http")
.time
at the beginning of the file to calculate startup and processing times.When you run the application and make a request, the middleware prints the endpoint URL and the processing time in seconds to the console. This log helps to understand endpoint performance and identify potential bottlenecks.
As a challenge, it is suggested to create an additional middleware that prints on the console all the headers sent in each request. This exercise allows to visualize the information of the headers and to better understand the structure of the requests.
Contributions 5
Questions 0
Want to see more contributions, questions and answers from the community?