Bird
Raised Fist0
FastAPIframework~10 mins

API key authentication in FastAPI - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
ADepends
BFastAPI
CRequest
DHTTPException
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request instead of FastAPI
Using HTTPException instead of FastAPI
Not importing anything
2fill in blank
medium

Complete the code to define the API key header name.

FastAPI
API_KEY_NAME = "[1]"
Drag options to blanks, or click blank then click option'
AX-API-KEY
BAuthorization
CContent-Type
DUser-Agent
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Authorization' header instead
Using 'Content-Type' header
Using 'User-Agent' header
3fill in blank
hard

Fix the error in the dependency function to get the API key from headers.

FastAPI
from fastapi import Header, HTTPException

async def get_api_key(api_key: str = Header(..., alias="[1]")):
    if api_key != "secret123":
        raise HTTPException(status_code=401, detail="Invalid API Key")
    return api_key
Drag options to blanks, or click blank then click option'
Aapi_key
BAuthorization
CX-API-KEY
DapiKey
Attempts:
3 left
💡 Hint
Common Mistakes
Using the parameter name instead of the header name
Using 'Authorization' instead of 'X-API-KEY'
Using a wrong header name
4fill in blank
hard

Fill both blanks to protect the endpoint with API key dependency.

FastAPI
from fastapi import Depends

@app.get("/secure-data")
async def secure_data(api_key: str = Depends([1])):
    return {"message": "Access granted with key: " + [2]
Drag options to blanks, or click blank then click option'
Aget_api_key
Bapi_key
CAPI_KEY_NAME
DHeader
Attempts:
3 left
💡 Hint
Common Mistakes
Using Header instead of get_api_key in Depends
Using API_KEY_NAME instead of api_key in return
Not using Depends at all
5fill in blank
hard

Fill all three blanks to create a complete FastAPI app with API key authentication.

FastAPI
from fastapi import FastAPI, Header, HTTPException, Depends

app = FastAPI()

API_KEY_NAME = "X-API-KEY"

async def get_api_key(api_key: str = Header(..., alias="[1]")):
    if api_key != "secret123":
        raise HTTPException(status_code=401, detail="Invalid API Key")
    return api_key

@app.get("/data")
async def read_data(api_key: str = Depends([2])):
    return {"message": "Hello, your API key is " + [3]
Drag options to blanks, or click blank then click option'
AX-API-KEY
Bget_api_key
Capi_key
DAuthorization
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong header name in Header()
Not using Depends or wrong function in Depends
Using wrong variable name in return

Practice

(1/5)
1. What is the main purpose of using API key authentication in a FastAPI application?
easy
A. To restrict access to the API by requiring a secret key in requests
B. To speed up the API response time
C. To automatically generate API documentation
D. To format the API response as JSON

Solution

  1. Step 1: Understand API key authentication purpose

    API key authentication is used to protect APIs by requiring a secret key from clients.
  2. Step 2: Identify the correct purpose in options

    Only To restrict access to the API by requiring a secret key in requests describes restricting access using a secret key, which matches the purpose.
  3. Final Answer:

    To restrict access to the API by requiring a secret key in requests -> Option A
  4. Quick Check:

    API key authentication = restrict access [OK]
Hint: API keys control who can use the API [OK]
Common Mistakes:
  • Confusing API key with speeding up API
  • Thinking API key generates docs
  • Assuming API key changes response format
2. Which FastAPI import is used to extract an API key from the request header?
easy
A. from fastapi import Header
B. from fastapi.security import APIKeyHeader
C. from fastapi.security import OAuth2PasswordBearer
D. from fastapi import Depends

Solution

  1. Step 1: Identify the correct security class for API key in header

    FastAPI provides APIKeyHeader to extract API keys from headers.
  2. Step 2: Compare options to find the exact import

    from fastapi.security import APIKeyHeader imports APIKeyHeader from fastapi.security, which is correct.
  3. Final Answer:

    from fastapi.security import APIKeyHeader -> Option B
  4. Quick Check:

    API key header extractor = APIKeyHeader [OK]
Hint: API keys in headers use APIKeyHeader import [OK]
Common Mistakes:
  • Using OAuth2PasswordBearer for API keys
  • Confusing Header with APIKeyHeader
  • Missing import from fastapi.security
3. 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'}
medium
A. 403 Forbidden with detail 'Invalid API Key'
B. 200 OK with message 'Access granted'
C. 500 Internal Server Error
D. 422 Unprocessable Entity error

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]
Hint: Missing required header causes 422 error [OK]
Common Mistakes:
  • Assuming missing key triggers 403 error
  • Expecting 200 OK without key
  • Thinking server crashes with 500 error
4. Identify the error in this FastAPI API key authentication code:
from fastapi import FastAPI, Security, HTTPException
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 = api_key_header):
    if api_key != 'topsecret':
        raise HTTPException(status_code=401, detail='Unauthorized')
    return {'data': 'Here is your data'}
medium
A. Missing Security() wrapper around api_key_header in function parameter
B. Incorrect HTTP status code for unauthorized access
C. APIKeyHeader should be named 'Authorization' instead of 'X-API-Key'
D. Function should be synchronous, not async

Solution

  1. Step 1: Check how APIKeyHeader is used in dependency

    FastAPI requires Security() to wrap APIKeyHeader for dependency injection.
  2. Step 2: Identify missing Security() in parameter

    The code uses api_key: str = api_key_header instead of Security(api_key_header).
  3. Final Answer:

    Missing Security() wrapper around api_key_header in function parameter -> Option A
  4. Quick Check:

    APIKeyHeader needs Security() [OK]
Hint: Wrap APIKeyHeader with Security() in parameters [OK]
Common Mistakes:
  • Omitting Security() causes injection failure
  • Using wrong header name is not an error here
  • HTTP status 401 is acceptable for unauthorized
5. You want to secure multiple endpoints in FastAPI using the same API key header. Which approach is best to avoid repeating code?
hard
A. Use a global variable to store the API key and check it manually in each endpoint
B. Copy the API key check code inside every endpoint function
C. Create a reusable dependency function that checks the API key and use Security() with it
D. Disable authentication and rely on client honesty

Solution

  1. Step 1: Understand code reuse in FastAPI dependencies

    FastAPI encourages reusable dependencies to share logic like API key checks.
  2. Step 2: Identify best practice for API key checks

    Creating a dependency function with Security() allows clean reuse across endpoints.
  3. Final Answer:

    Create a reusable dependency function that checks the API key and use Security() with it -> Option C
  4. Quick Check:

    Reusable dependency = clean, DRY code [OK]
Hint: Use reusable dependency functions for API key checks [OK]
Common Mistakes:
  • Copy-pasting code leads to duplication
  • Using global variables breaks encapsulation
  • Disabling authentication is insecure