Complete the code to create a basic FastAPI app instance.
from fastapi import [1] app = [1]()
The FastAPI class is used to create the app instance. This is the starting point for any FastAPI application.
Complete the code to define a GET endpoint that returns a welcome message.
@app.[1]("/") async def read_root(): return {"message": "Welcome to production-ready FastAPI!"}
The @app.get decorator defines a GET HTTP method endpoint. This is used to read or fetch data.
Fix the error in the code to correctly run the FastAPI app with Uvicorn.
import uvicorn if __name__ == "__main__": uvicorn.run("main:[1]", host="127.0.0.1", port=8000, reload=True)
The string passed to uvicorn.run should be the module name and the FastAPI app instance name separated by a colon. Usually, the app instance is named app.
Fill both blanks to add middleware that logs requests and responses.
from fastapi.middleware.[1] import [2] app.add_middleware([2])
Middleware for logging requests is often custom or named LoggerMiddleware. The import path includes 'logging' for this example.
Fill all three blanks to create a dependency that checks an API key in headers.
from fastapi import Header, HTTPException, [1] async def verify_api_key(api_key: str = [2](alias="X-API-Key")): if api_key != "secret123": raise [3](status_code=401, detail="Invalid API Key")
Dependencies in FastAPI use Depends. The API key is extracted from headers using Header. If invalid, an HTTPException is raised.