Module 29 - FastAPI Introduction
FastAPI is a modern, fast web framework for building APIs with Python, featuring automatic interactive documentation and data validation.
1. Introduction
Installation
pip install fastapi uvicorn
Why FastAPI?
✅ Fast performance (comparable to NodeJS/Go)
✅ Automatic API documentation
✅ Type hints and validation
✅ Async support built-in
✅ Easy to learn
2. Hello World
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}
# Run with: uvicorn main:app --reload
Visit:
- API:
http://127.0.0.1:8000/ - Docs:
http://127.0.0.1:8000/docs
3. Path and Query Parameters
from fastapi import FastAPI
app = FastAPI()
# Path parameter
@app.get("/users/{user_id}")
def read_user(user_id: int):
return {"user_id": user_id}
# Query parameters
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
# Combined
@app.get("/users/{user_id}/items/")
def read_user_items(user_id: int, skip: int = 0):
return {"user_id": user_id, "skip": skip}
4. Pydantic Models
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.post("/items/")
def create_item(item: Item):
return {"item": item, "message": "Item created"}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_id": item_id, "item": item}
5. CRUD Operations
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
app = FastAPI()
class User(BaseModel):
id: int
name: str
email: str
users_db = []
@app.post("/users/", response_model=User)
def create_user(user: User):
users_db.append(user)
return user
@app.get("/users/", response_model=List[User])
def get_users():
return users_db
@app.get("/users/{user_id}", response_model=User)
def get_user(user_id: int):
for user in users_db:
if user.id == user_id:
return user
raise HTTPException(status_code=404, detail="User not found")
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
for i, user in enumerate(users_db):
if user.id == user_id:
users_db.pop(i)
return {"message": "User deleted"}
raise HTTPException(status_code=404, detail="User not found")
Summary
✅ FastAPI is modern and fast
✅ Automatic documentation with Swagger UI
✅ Pydantic models for validation
✅ Type hints throughout
✅ Async support built-in
Next Steps
In Module 30, you'll learn:
- Testing with pytest
- Unit tests and fixtures
- Test coverage
- Mocking and assertions
Practice Exercises
- Create a complete REST API for a todo app
- Build an API with authentication
- Implement pagination for list endpoints
- Create a blog API with posts and comments
- Build a file upload API :::