Consider this FastAPI endpoint that requires an API key for access. What will the endpoint return if the correct API key is sent in the header?
from fastapi import FastAPI, Security, HTTPException from fastapi.security.api_key import APIKeyHeader app = FastAPI() API_KEY = "secret123" api_key_header = APIKeyHeader(name="X-API-Key") @app.get("/secure-data") async def secure_data(api_key: str = Security(api_key_header)): if api_key == API_KEY: return {"message": "Access granted"} else: raise HTTPException(status_code=403, detail="Invalid API Key")
Think about what the function returns when the API key matches the expected value.
If the API key sent in the header matches the expected key, the endpoint returns a JSON message confirming access. Otherwise, it raises a 403 error.
Which of the following API key dependency declarations in FastAPI will cause a syntax error?
from fastapi.security.api_key import APIKeyHeader # Assume API_KEY_HEADER_NAME = "X-API-Key"
Look for incomplete or missing arguments in function calls.
Option D is missing a value for the 'name' parameter, causing a syntax error.
Given this FastAPI endpoint using APIKeyHeader, what HTTP status code will the client receive if the request omits the API key header?
from fastapi import FastAPI, Security from fastapi.security.api_key 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 {"data": "secret info"}
Think about how FastAPI's Security dependencies behave when required headers are missing.
When the API key header is missing, FastAPI returns a 401 Unauthorized error by default.
Examine the code below. Even when the correct API key is sent, the endpoint always raises a 403 error. What is the cause?
from fastapi import FastAPI, Security, HTTPException from fastapi.security.api_key import APIKeyHeader app = FastAPI() API_KEY = "secret123" api_key_header = APIKeyHeader(name="X-API-Key") @app.get("/check") async def check_key(api_key: str = Security(api_key_header)): if api_key is API_KEY: return {"status": "valid"} else: raise HTTPException(status_code=403, detail="Invalid API Key")
Check how string comparison works in Python.
Using 'is' compares object identity, not string content. This causes the condition to fail even if strings have the same content.
Why is it a bad idea to include API keys directly in frontend JavaScript code that runs in browsers?
Think about what users can do with browser developer tools.
Any code running in the browser is visible to users, so API keys included there can be copied and misused.