Bird
Raised Fist0
FastAPIframework~5 mins

Custom middleware creation in FastAPI - Cheat Sheet & Quick Revision

Choose your learning style10 modes available

Start learning this pattern below

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
Recall & Review
beginner
What is middleware in FastAPI?
Middleware is a function that runs before and/or after each request. It can modify requests, responses, or perform actions like logging or authentication.
Click to reveal answer
intermediate
How do you create a custom middleware in FastAPI?
You create a class with an __init__ and async __call__ method. The __call__ method receives the request and calls the next handler, allowing you to run code before and after the request.
Click to reveal answer
beginner
What is the role of the 'call_next' function in FastAPI middleware?
call_next is a function that processes the request and returns the response from the next middleware or endpoint. It lets your middleware continue the request chain.
Click to reveal answer
intermediate
Why should middleware be asynchronous in FastAPI?
FastAPI is built on async Python. Middleware should be async to avoid blocking the server and to handle many requests efficiently.
Click to reveal answer
beginner
Give an example use case for custom middleware in FastAPI.
Custom middleware can log request times, check authentication tokens, add headers to responses, or handle CORS policies.
Click to reveal answer
What method must a custom FastAPI middleware class implement to handle requests?
Ahandle_request
B__init__
C__call__
Dprocess_request
In FastAPI middleware, what does the 'call_next' function do?
AProcesses the request and returns the response from the next handler
BStops the request from continuing
CCreates a new request
DModifies the request headers only
Why is it important for FastAPI middleware to be asynchronous?
ATo automatically cache responses
BTo avoid blocking the server and handle many requests efficiently
CTo make the code shorter
DBecause synchronous code is not allowed
Which of these is NOT a typical use case for custom middleware in FastAPI?
ARendering HTML templates
BLogging request times
CAdding headers to responses
DChecking authentication tokens
How do you add a custom middleware class to a FastAPI app?
AUse app.include_router with middleware
BCall middleware() function directly
CImport middleware in main.py only
DUse app.add_middleware with the middleware class
Explain how to create and add a custom middleware in FastAPI. Include the key methods and how the request flow works.
Think about how middleware wraps around requests and responses.
You got /4 concepts.
    Describe three practical reasons to use custom middleware in a FastAPI application.
    Middleware acts like a checkpoint for every request.
    You got /3 concepts.

      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

      1. Step 1: Understand middleware role

        Middleware runs code around request processing, before and after the main handler.
      2. Step 2: Identify correct purpose

        Custom middleware is not for database or templates but for request/response handling.
      3. Final Answer:

        To run code before and after each request is processed -> Option D
      4. 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

      1. Step 1: Recall FastAPI middleware structure

        Custom middleware classes override the dispatch method to handle requests.
      2. Step 2: Match method names

        Only dispatch is the correct method name; others are invalid in FastAPI middleware.
      3. Final Answer:

        dispatch -> Option A
      4. Quick Check:

        dispatch method overrides middleware behavior [OK]
      Hint: dispatch handles request and response in middleware [OK]
      Common Mistakes:
      • Using incorrect method names like handle_request
      • Confusing middleware methods with route handlers
      • Forgetting to override dispatch method
      3. Given this middleware code snippet, what will be printed when a request is processed?
      class LogMiddleware:
          async def dispatch(self, request, call_next):
              print('Before request')
              response = await call_next(request)
              print('After request')
              return response
      medium
      A. Only Before request printed
      B. Before request printed, then After request printed after response
      C. Only After request printed
      D. No output printed

      Solution

      1. Step 1: Analyze dispatch method flow

        Print 'Before request' runs before calling next handler, 'After request' runs after awaiting response.
      2. Step 2: Understand async call_next behavior

        call_next processes the request and returns response; code after await runs after response is ready.
      3. Final Answer:

        Before request printed, then After request printed after response -> Option B
      4. Quick Check:

        Print before and after call_next = B [OK]
      Hint: Code before await runs first, after await runs last [OK]
      Common Mistakes:
      • Thinking 'After request' prints before response
      • Ignoring async await order
      • Assuming only one print runs
      4. Identify the error in this custom middleware code:
      class MyMiddleware:
          async def dispatch(self, request):
              response = await call_next(request)
              return response
      medium
      A. Response must be created manually, not awaited
      B. dispatch method should not be async
      C. Missing call_next parameter in dispatch method
      D. Middleware class must inherit from BaseHTTPMiddleware

      Solution

      1. Step 1: Check dispatch method signature

        dispatch must accept both request and call_next parameters to call next handler.
      2. Step 2: Identify missing parameter

        Code lacks call_next parameter, causing runtime error when calling call_next(request).
      3. Final Answer:

        Missing call_next parameter in dispatch method -> Option C
      4. 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?
      hard
      A. class TimerMiddleware: async def dispatch(self, request, call_next): start = time.time() response = await call_next(request) process_time = time.time() - start response.headers['X-Process-Time'] = str(process_time) return response
      B. class TimerMiddleware: async def dispatch(self, request): start = time.time() response = await call_next(request) response.headers['X-Process-Time'] = str(time.time() - start) return response
      C. class TimerMiddleware: def dispatch(self, request, call_next): start = time.time() response = call_next(request) response.headers['X-Process-Time'] = str(time.time() - start) return response
      D. class TimerMiddleware: async def dispatch(self, request, call_next): response = await call_next(request) response.headers['X-Process-Time'] = time.time() return response

      Solution

      1. Step 1: Check dispatch method signature and async usage

        dispatch must be async and accept request and call_next parameters.
      2. Step 2: Verify timing and header addition

        Start time before await call_next, calculate duration after, add header as string.
      3. Step 3: Identify correct code snippet

        class TimerMiddleware: async def dispatch(self, request, call_next): start = time.time() response = await call_next(request) process_time = time.time() - start response.headers['X-Process-Time'] = str(process_time) return response correctly implements timing, async, and header addition.
      4. Final Answer:

        The code snippet that correctly adds X-Process-Time header -> Option A
      5. Quick Check:

        Async dispatch with timing and header = A [OK]
      Hint: Measure time before and after await call_next, add header [OK]
      Common Mistakes:
      • Missing call_next parameter
      • Not awaiting call_next
      • Adding header before timing calculation
      • Using synchronous dispatch method