Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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
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
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
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
Hint
Use @app.get("/") decorator and define async def read_root() returning the dictionary.
Practice
(1/5)
1. What is the main purpose of creating custom middleware in FastAPI?
easy
A. To handle user authentication only
B. To define database models
C. To create HTML templates
D. To run code before and after each request is processed
Solution
Step 1: Understand middleware role
Middleware runs code around request processing, before and after the main handler.
Step 2: Identify correct purpose
Custom middleware is not for database or templates but for request/response handling.
Final Answer:
To run code before and after each request is processed -> Option D
Quick Check:
Middleware = pre/post request code [OK]
Hint: Middleware wraps requests to add extra processing [OK]
Common Mistakes:
Confusing middleware with database or template code
Thinking middleware only handles authentication
Believing middleware runs only after requests
2. Which method must be overridden when creating a custom middleware class in FastAPI?
easy
A. dispatch
B. execute
C. process
D. handle_request
Solution
Step 1: Recall FastAPI middleware structure
Custom middleware classes override the dispatch method to handle requests.
Step 2: Match method names
Only dispatch is the correct method name; others are invalid in FastAPI middleware.
D. Middleware class must inherit from BaseHTTPMiddleware
Solution
Step 1: Check dispatch method signature
dispatch must accept both request and call_next parameters to call next handler.
Step 2: Identify missing parameter
Code lacks call_next parameter, causing runtime error when calling call_next(request).
Final Answer:
Missing call_next parameter in dispatch method -> Option C
Quick Check:
dispatch(request, call_next) required [OK]
Hint: dispatch needs call_next argument to forward requests [OK]
Common Mistakes:
Omitting call_next parameter
Making dispatch synchronous
Not inheriting middleware base class (optional but recommended)
5. You want to create a middleware that adds a custom header 'X-Process-Time' showing how long the request took. Which code snippet correctly implements this?