python --version
pip install fastapi uvicorn pydantic
Create a FastAPI application that auto-generates a comprehensive OpenAPI 3.1 specification with examples, security schemes, and error schemas.
1 from typing import Any 2 from fastapi import FastAPI, HTTPException, Security 3 from fastapi.security import APIKeyHeader 4 from pydantic import BaseModel, Field 5 6 api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False) 7 8 app = FastAPI( 9 title="Product Catalog API", 10 version="2.0.0", 11 description="Manages product inventory with full CRUD operations.", 12 contact={"name": "API Team", "email": "api@example.com"}, 13 license_info={"name": "MIT"}, 14 ) 15 16 class ErrorResponse(BaseModel): 17 error: str 18 code: int 19 detail: str 20 21 class ProductCreate(BaseModel): 22 name: str = Field(..., min_length=1, max_length=100, examples=["Laptop Pro 16"]) 23 price: float = Field(..., gt=0, examples=[999.99]) 24 category: str = Field(..., examples=["electronics"]) 25 26 class Product(ProductCreate): 27 id: int = Field(..., examples=[42]) 28 created_at: str = Field(..., examples=["2024-01-15T10:30:00Z"]) 29 30 products_db: dict[int, Product] = {} 31 32 @app.post( 33 "/products", 34 response_model=Product, 35 status_code=201, 36 responses={ 37 400: {"model": ErrorResponse, "description": "Invalid input"}, 38 401: {"model": ErrorResponse, "description": "Missing or invalid API key"}, 39 }, 40 summary="Create a new product", 41 tags=["products"], 42 ) 43 async def create_product(product: ProductCreate, api_key: str | None = Security(api_key_header)): 44 if not api_key: 45 raise HTTPException(status_code=401, detail="API key required") 46 new_id = len(products_db) + 1 47 new_product = Product(id=new_id, created_at="2024-01-15T10:30:00Z", **product.model_dump()) 48 products_db[new_id] = new_product 49 return new_product 50 51 @app.get( 52 "/products/{product_id}", 53 response_model=Product, 54 responses={404: {"model": ErrorResponse, "description": "Product not found"}}, 55 summary="Get a product by ID", 56 tags=["products"], 57 ) 58 async def get_product(product_id: int): 59 if product_id not in products_db: 60 raise HTTPException(status_code=404, detail=f"Product {product_id} not found") 61 return products_db[product_id] 62
Sign in to share your feedback and join the discussion.