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
Why API security is critical
📖 Scenario: You are building a simple FastAPI application that exposes an API endpoint for users to get their profile information. Since this API will be accessed over the internet, it is important to secure it so only authorized users can get their data.
🎯 Goal: Build a FastAPI app with a protected API endpoint that requires a simple API key for access. This will show why API security is critical to prevent unauthorized access.
📋 What You'll Learn
Create a FastAPI app instance
Add a variable to store a secret API key
Create an endpoint /profile that checks the API key in request headers
Return user profile data only if the API key matches
Return an error response if the API key is missing or wrong
💡 Why This Matters
🌍 Real World
APIs are often exposed to the internet and can be attacked or misused. Securing APIs with keys or tokens ensures only authorized users can access sensitive data or actions.
💼 Career
Understanding API security basics is essential for backend developers, API designers, and anyone working with web services to protect user data and maintain trust.
Progress0 / 4 steps
1
Create FastAPI app instance
Create a FastAPI app instance called app by importing FastAPI from fastapi and calling FastAPI().
FastAPI
Hint
Use from fastapi import FastAPI and then app = FastAPI().
2
Add secret API key variable
Add a variable called API_KEY and set it to the string "secret123".
FastAPI
Hint
Just create a variable API_KEY and assign it the string "secret123".
3
Create protected /profile endpoint
Create a GET endpoint /profile using @app.get("/profile"). Inside the function get_profile, accept a parameter api_key from the request header using Header from fastapi. Check if api_key equals API_KEY. If yes, return a dictionary with {"user": "Alice", "email": "alice@example.com"}. If not, raise HTTPException with status code 401 and detail "Unauthorized". Remember to import Header and HTTPException from fastapi.
FastAPI
Hint
Use @app.get("/profile") and a function with api_key from headers. Compare it to API_KEY and raise HTTPException if it does not match.
4
Complete app with security check
Ensure the full code includes imports for FastAPI, Header, and HTTPException, the app instance, the API_KEY variable, and the /profile endpoint with the API key check as described.
FastAPI
Hint
Make sure all parts are included and the code matches the previous step's solution.
Practice
(1/5)
1. Why is API security critical when building applications with FastAPI?
easy
A. It reduces the size of the API responses.
B. It makes the API run faster.
C. It automatically fixes bugs in the code.
D. It prevents unauthorized users from accessing sensitive data.
Solution
Step 1: Understand the purpose of API security
API security is designed to stop unauthorized users from accessing or changing data they shouldn't see.
Step 2: Relate to FastAPI's use case
FastAPI uses security measures like token checks to protect data and user privacy.
Final Answer:
It prevents unauthorized users from accessing sensitive data. -> Option D
Quick Check:
API security = prevent unauthorized access [OK]
Hint: Think: security means stopping unwanted access [OK]
Common Mistakes:
Confusing security with performance improvements
Believing security fixes bugs automatically
Thinking security reduces data size
2. Which FastAPI code snippet correctly adds a security dependency to check an API token?
easy
A. from fastapi import Depends, Security
from fastapi.security import APIKeyHeader
api_key_header = APIKeyHeader(name="Authorization")
@app.get("/secure")
async def secure_route(api_key: str = Security(api_key_header)):
return {"key": api_key}
B. from fastapi import Depends
@app.get("/secure")
async def secure_route(token: str = Depends("Authorization")):
return {"token": token}
C. from fastapi import Security
@app.get("/secure")
async def secure_route(api_key: str = Security("Authorization")):
return {"key": api_key}
D. from fastapi import Depends
@app.get("/secure")
async def secure_route(api_key: str):
return {"key": api_key}
Solution
Step 1: Identify correct use of Security dependency
FastAPI uses Security with APIKeyHeader to check headers like Authorization tokens.
Step 2: Check code correctness
from fastapi import Depends, Security
from fastapi.security import APIKeyHeader
api_key_header = APIKeyHeader(name="Authorization")
@app.get("/secure")
async def secure_route(api_key: str = Security(api_key_header)):
return {"key": api_key} correctly imports APIKeyHeader, creates a header dependency, and uses Security to enforce it.
Final Answer:
Code using APIKeyHeader and Security dependency correctly. -> Option A
Quick Check:
Security dependency with APIKeyHeader = from fastapi import Depends, Security
from fastapi.security import APIKeyHeader
api_key_header = APIKeyHeader(name="Authorization")
@app.get("/secure")
async def secure_route(api_key: str = Security(api_key_header)):
return {"key": api_key} [OK]
Hint: Look for APIKeyHeader and Security usage together [OK]
Common Mistakes:
Using Depends with a string instead of a dependency
Missing APIKeyHeader import or usage
Not using Security for header token checks
3. Given this FastAPI route, what will be the response if the client sends a request without the required API key header?