Back to Blog

FastAPI Crash Course - Modern Python API Development

Sandy LaneSandy Lane

Video: FastAPI Crash Course - Modern Python API Development by Traversy Media

Watch full page →

FastAPI Crash Course - Modern Python API Development

FastAPI is a modern, high-performance Python framework designed for building APIs quickly and efficiently. In this crash course, you'll learn how to set up a FastAPI project, create routes, handle requests with Pydantic models, and explore built-in interactive API documentation.

Code

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# Define a Pydantic model for data validation
class Item(BaseModel):
  name: str
  description: str | None = None
  price: float
  tax: float | None = None

# Create a GET route
@app.get("/")
async def read_root():
  return {"message": "Welcome to FastAPI!"}

# Create a GET route with path parameter
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
  return {"item_id": item_id, "q": q}

# Create a POST route to create an item
@app.post("/items/")
async def create_item(item: Item):
  total_price = item.price + (item.tax or 0)
  return {"name": item.name, "total_price": total_price}

Key Points

  • FastAPI uses Python type hints and Pydantic models for automatic data validation and serialization.
  • Routes are defined with decorators like @app.get() and @app.post(), supporting path and query parameters.
  • FastAPI automatically generates interactive Swagger UI docs accessible at /docs.
  • Asynchronous route handlers improve performance for I/O-bound operations.
  • Creating a virtual environment and installing FastAPI with Uvicorn is the recommended setup for development.