FastAPI โ Building REST APIs
Build high-performance REST APIs with FastAPI โ routing, Pydantic schemas, dependency injection, background tasks, and auto OpenAPI docs.
Part 1: What You Will Learn
- Create a FastAPI application and route functions.
- Validate request bodies with Pydantic models.
- Implement basic CRUD endpoints.
- Run the API with Uvicorn and inspect automatic OpenAPI documentation.
Part 2: Key Concepts
FastAPI maps HTTP routes to normal Python functions and uses type hints plus Pydantic models for validation. It automatically creates an OpenAPI schema and interactive documentation, which makes it convenient for learning and building typed REST APIs.
Part 3: Topic-Specific Code Examples
# Install once: pip install fastapi uvicorn
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field
app = FastAPI(title="Product API")
class ProductCreate(BaseModel):
name: str = Field(min_length=2)
price: float = Field(gt=0)
class Product(ProductCreate):
id: int
products: dict[int, Product] = {}
next_id = 1
@app.get("/products", response_model=list[Product])
def list_products() -> list[Product]:
return list(products.values())
@app.get("/products/{product_id}", response_model=Product)
def get_product(product_id: int) -> Product:
product = products.get(product_id)
if product is None:
raise HTTPException(status_code=404, detail="Product not found")
return product
@app.post("/products", response_model=Product, status_code=status.HTTP_201_CREATED)
def create_product(data: ProductCreate) -> Product:
global next_id
product = Product(id=next_id, **data.model_dump())
products[next_id] = product
next_id += 1
return product
@app.delete("/products/{product_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_product(product_id: int) -> None:
if product_id not in products:
raise HTTPException(status_code=404, detail="Product not found")
del products[product_id]uvicorn main:app --reload # Open in a browser: # http://127.0.0.1:8000/docs # http://127.0.0.1:8000/redoc
Part 4: How the Example Works
The request model rejects blank names and non-positive prices before the route function runs. Path parameters such as product_id are also typed. The in-memory dictionary keeps the first example simple; a production API would normally store data in a database, which is covered in Lesson 26.
Part 5: Hands-On Practice
Mini project โ Student API. Create StudentCreate and Student models with name, course, and mark. Add endpoints to list students, retrieve one student, create a student, update a mark, and delete a student. Test each route through /docs.
Part 6: Next Steps
Run and modify the examples in Visual Studio 2026, then continue to Lesson 25. Return to Python Tutorial Home to review the complete curriculum.