Learn to build interactive API documentation with FastAPI using OpenAPI, including setting up a Fake Data API and customizing Swagger UI and Redoc interfaces.
Use this file to discover all available pages before exploring further.
Learn how to build and refine interactive API docs using FastAPI’s built-in OpenAPI support. You’ll set up a simple “Fake Data API,” write clear docstrings, and customize the generated Swagger UI and Redoc interfaces.
Python 3.7 or higher
A virtual environment with fastapi, uvicorn, and pydantic installed
# main.py (continued)def fetch_fake_data(count: int) -> List[Dict]: """ Retrieve a random selection of fake data entries. Args: count (int): Number of records (1–1000). Returns: List[Dict]: Fake data entries. Raises: HTTPException(400): If count is out of range. HTTPException(404): If no records are found. """ if not (1 <= count <= 1000): raise HTTPException(status_code=400, detail="Count must be between 1 and 1000") with get_db_connection() as conn: cursor = conn.cursor() cursor.execute( """ SELECT first_name, last_name, email_address, age, city, occupation FROM fake_data ORDER BY RANDOM() LIMIT ? """, (count,), ) rows = cursor.fetchall() if not rows: raise HTTPException(status_code=404, detail="No data entries found") return [dict(row) for row in rows]
Requests exceeding 1000 entries will return a 400 Bad Request. Always validate count before calling the endpoint.
# main.py (continued)from fastapi.responses import JSONResponse@app.post( "/api/v1/getfakedata", response_model=List[Dict], tags=["Fake Data Generation"], summary="Generate random fake personal data entries",)async def get_fake_data(request: DataRequest): """ Generate and return fake personal data. - **count**: Number of entries (min: 1, max: 1000) **Responses** - 200: Successfully retrieved data - 400: Invalid parameters - 404: No records found - 500: Internal server error """ data = fetch_fake_data(request.count) return JSONResponse(content=data)