0
0
FastAPIframework~10 mins

Why middleware processes requests globally in FastAPI - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a middleware function in FastAPI.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.middleware("[1]")
async def log_requests(request, call_next):
    response = await call_next(request)
    return response
Drag options to blanks, or click blank then click option'
Arequest
Bhttp
Cmiddleware
Droute
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'request' or 'route' instead of 'http' in the decorator.
Forgetting to make the middleware function async.
2fill in blank
medium

Complete the code to call the next middleware or route handler inside the middleware.

FastAPI
async def log_requests(request, call_next):
    response = await [1](request)
    return response
Drag options to blanks, or click blank then click option'
Arequest
Bhandle_request
Cnext_call
Dcall_next
Attempts:
3 left
💡 Hint
Common Mistakes
Calling 'request' or other variables instead of 'call_next'.
Not using await before call_next.
3fill in blank
hard

Fix the error in the middleware function to ensure it processes all requests globally.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.middleware("http")
async def [1](request, call_next):
    response = await call_next(request)
    return response
Drag options to blanks, or click blank then click option'
Alog_requests
Bprocess_request
Chandle_request
Dmiddleware_func
Attempts:
3 left
💡 Hint
Common Mistakes
Using generic or unclear function names.
Using reserved keywords as function names.
4fill in blank
hard

Fill both blanks to create a middleware that adds a custom header to every response.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.middleware("http")
async def add_header(request, call_next):
    response = await call_next(request)
    response.headers[[1]] = [2]
    return response
Drag options to blanks, or click blank then click option'
A"X-Custom-Header"
B"Content-Type"
C"Hello"
D"application/json"
Attempts:
3 left
💡 Hint
Common Mistakes
Using standard headers like 'Content-Type' instead of a custom one.
Not using quotes around header names and values.
5fill in blank
hard

Fill both blanks to create a middleware that logs the request method and path before processing.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.middleware("http")
async def log_request_info(request, call_next):
    print(f"Request: [1] [2]")
    response = await call_next(request)
    return response
Drag options to blanks, or click blank then click option'
Arequest.method
Brequest.url.path
Crequest.headers
Drequest.body
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'request.headers' or 'request.body' instead of method and path for logging.
Not using f-string formatting correctly.