from fastapi import Depends, HTTPException from sqlalchemy.orm import Session from .database import engine, Base, get_db from .models import DBProduct Base.metadata.create_all(bind=engine) @app.post("/products/") def add_product(name: str, price: float, db: Session = Depends(get_db)): product = DBProduct(name=name, price=price) db.add(product) db.commit() db.refresh(product) return product Use code with caution. 7. Dependency Injection System
Once the server is running, FastAPI automatically generates interactive documentation. Open your browser and navigate to:
FROM python:3.10-slim WORKDIR /app COPY ./requirements.txt /app/requirements.txt RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt COPY ./app /app/app CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Use code with caution. Save This Guide as a PDF fastapi tutorial pdf
from fastapi.middleware.cors import CORSMiddleware origins = [ "http://localhost:3000", "https://myproductionfrontend.com", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) Use code with caution. 10. Summary Cheat Sheet Syntax Snippet Primary Purpose @app.get("/route/id") Extracts unique resource identifiers from URLs Query Parameters def read(limit: int = 10): Filters, paginates, or searches data results Pydantic Validation class Model(BaseModel): Validates, sanitizes, and enforces incoming request bodies Response Model response_model=Schema Filters out unauthorized or sensitive fields from outputs Dependencies Depends(dependency_func)
When you need to send data from a client to your API, you send it as a . FastAPI relies on Pydantic to define the data structure, validate input data, and serialize output data. Defining a Schema from fastapi import Depends, HTTPException from sqlalchemy
def common_parameters(q: str = None, skip: int = 0, limit: int = 10):return "q": q, "skip": skip, "limit": limit
Open your browser and navigate to http://127.0.0.1:8000 . You will see the JSON response: "message": "Welcome to the FastAPI Tutorial Handbook!" . 📖 Exploiting Interactive Interactive Documentation Open your browser and navigate to: FROM python:3
Any arguments in your function that are not part of the URL path are automatically treated as query parameters.
When migrating your FastAPI application from development to a production server, adhere to this operational checklist: