Bird
0
0

Given this FastAPI route, what will be the response if the client sends a request without the required API key header?

medium📝 component behavior Q13 of 15
FastAPI - Authentication and Security
Given this FastAPI route, what will be the response if the client sends a request without the required API key header?
from fastapi import FastAPI, Security
from fastapi.security import APIKeyHeader

app = FastAPI()
api_key_header = APIKeyHeader(name="X-API-Key")

@app.get("/data")
async def get_data(api_key: str = Security(api_key_header)):
    return {"message": "Access granted", "key": api_key}
AHTTP 404 Not Found error
B{"message": "Access granted", "key": "some_key"}
CHTTP 403 Forbidden error
D{"message": "Access denied"}
Step-by-Step Solution
Solution:
  1. Step 1: Understand APIKeyHeader behavior

    APIKeyHeader raises a 403 error if the required header is missing in the request.
  2. Step 2: Analyze the route response

    The route returns data only if the API key header is present; otherwise, FastAPI returns 403 Forbidden automatically.
  3. Final Answer:

    HTTP 403 Forbidden error -> Option C
  4. Quick Check:

    Missing API key header = 403 error [OK]
Quick Trick: Missing API key header causes 403 error in FastAPI [OK]
Common Mistakes:
MISTAKES
  • Expecting 404 error instead of 403
  • Assuming a custom message is returned automatically
  • Thinking the route runs without the header

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes