0
0
FastAPIframework~30 mins

Custom middleware creation in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom middleware creation
📖 Scenario: You are building a web API using FastAPI. You want to add a custom middleware that logs the time taken to process each request. This helps you understand how long your API takes to respond.
🎯 Goal: Create a custom middleware in FastAPI that measures and logs the time taken for each request.
📋 What You'll Learn
Create a FastAPI app instance
Define a custom middleware class that measures request processing time
Add the middleware to the FastAPI app
Create a simple GET endpoint to test the middleware
💡 Why This Matters
🌍 Real World
Custom middleware helps monitor and modify requests and responses in web APIs, useful for logging, authentication, and performance tracking.
💼 Career
Understanding middleware creation is essential for backend developers working with FastAPI or similar frameworks to build scalable and maintainable APIs.
Progress0 / 4 steps
1
Create FastAPI app instance
Write code to import FastAPI from fastapi and create an app instance called app.
FastAPI
Need a hint?

Use from fastapi import FastAPI and then app = FastAPI().

2
Define a custom middleware class
Write a class called TimingMiddleware that inherits from BaseHTTPMiddleware imported from starlette.middleware.base. Inside, define an async method dispatch that takes request and call_next as parameters. Use time.perf_counter() to record start and end times around call_next(request). Calculate the duration and print it with the message "Request took {duration} seconds".
FastAPI
Need a hint?

Import BaseHTTPMiddleware and time. Define dispatch method with timing logic.

3
Add the middleware to the FastAPI app
Add the TimingMiddleware to the app using app.add_middleware(TimingMiddleware).
FastAPI
Need a hint?

Use app.add_middleware(TimingMiddleware) to add the middleware.

4
Create a simple GET endpoint
Create a GET endpoint at path "/" using @app.get("/"). Define an async function called read_root that returns a dictionary {"message": "Hello World"}.
FastAPI
Need a hint?

Use @app.get("/") decorator and define async def read_root() returning the dictionary.