0
0
FastAPIframework~10 mins

API key authentication in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
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