Bird
0
0

Given this FastAPI code snippet, what will be the response if the client sends a request without the 'X-API-Key' header?

medium📝 component behavior Q13 of 15
FastAPI - Authentication and Security
Given this FastAPI code snippet, what will be the response if the client sends a request without the 'X-API-Key' header?
from fastapi import FastAPI, Security, HTTPException
from fastapi.security import APIKeyHeader

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

@app.get('/secure')
async def secure_endpoint(api_key: str = Security(api_key_header)):
    if api_key != 'secret123':
        raise HTTPException(status_code=403, detail='Invalid API Key')
    return {'message': 'Access granted'}
A403 Forbidden with detail 'Invalid API Key'
B200 OK with message 'Access granted'
C500 Internal Server Error
D422 Unprocessable Entity error
Step-by-Step Solution
Solution:
  1. Step 1: Understand Security dependency behavior

    If the required header 'X-API-Key' is missing, FastAPI returns a 422 error before entering the function.
  2. Step 2: Analyze the code's error handling

    The 403 error triggers only if the key is present but incorrect. Missing header causes 422 instead.
  3. Final Answer:

    422 Unprocessable Entity error -> Option D
  4. Quick Check:

    Missing header = 422 error [OK]
Quick Trick: Missing required header causes 422 error [OK]
Common Mistakes:
MISTAKES
  • Assuming missing key triggers 403 error
  • Expecting 200 OK without key
  • Thinking server crashes with 500 error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes