Complete the code to define a FastAPI app with a versioned path prefix.
from fastapi import FastAPI app = FastAPI() @app.get("/api/v[1]/items") def read_items(): return {"version": "[1]", "items": ["apple", "banana"]}
The version number in the path should be a simple number like '1' to form '/api/v1/items'.
Complete the code to add a header-based version check in FastAPI.
from fastapi import FastAPI, Header, HTTPException app = FastAPI() @app.get("/items") async def read_items(x_api_version: str = Header([1])): if x_api_version != "1": raise HTTPException(status_code=400, detail="Unsupported API version") return {"items": ["apple", "banana"]}
Setting the default to None means the header is optional and can be checked in the function.
Fix the error in the code to correctly implement query parameter versioning.
from fastapi import FastAPI, Query, HTTPException app = FastAPI() @app.get("/items") async def read_items(version: str = Query([1])): if version != "1": raise HTTPException(status_code=400, detail="Unsupported API version") return {"items": ["apple", "banana"]}
Setting the default to None makes the query parameter optional and allows checking its value.
Fill both blanks to create two FastAPI routers for version 1 and version 2 with path prefixes.
from fastapi import FastAPI, APIRouter app = FastAPI() router_v[1] = APIRouter(prefix="/api/v[1]") router_v[2] = APIRouter(prefix="/api/v[2]") @router_v[1].get("/items") async def get_items_v1(): return {"version": [1], "items": ["apple"]} @router_v[2].get("/items") async def get_items_v2(): return {"version": [2], "items": ["apple", "banana"]} app.include_router(router_v[1]) app.include_router(router_v[2])
Router names and prefixes use version numbers like '1' and '2' to separate API versions.
Fill all three blanks to implement header versioning with dependency injection in FastAPI.
from fastapi import FastAPI, Header, HTTPException, Depends app = FastAPI() def get_api_version([3]: str = Header([1])): if [3] not in ["1", "2"]: raise HTTPException(status_code=400, detail="Unsupported API version") return [3] @app.get("/items") async def read_items(version: str = Depends([2])): if version == "1": return {"items": ["apple"]} elif version == "2": return {"items": ["apple", "banana"]} return {"items": []}
Set header default to None, use dependency get_api_version, and parameter name x_api_version to access header value.