# FastAPI: A Modern Python Web Framework
## What is FastAPI?
FastAPI is a modern, high-performance web framework for building APIs with Python 3.6+ that's gaining massive popularity. Think of it as the "Formula 1 car" of Python web frameworks - it's incredibly fast and packed with features.
## Key Features That Make FastAPI Special
### 🚀 **Blazing Fast Performance**
- Built on **Starlette** (for web) and **Pydantic** (for data)
- Comparable to Node.js and Go in speed
- One of the fastest Python frameworks available
### 📝 **Type Hints Power**
```python
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None
app = FastAPI()
@app.post("/items/")
def create_item(item: Item): # Type hints = automatic validation!
return item
```
### 📚 **Automatic API Documentation**
- **Swagger UI** at `/docs`
- **ReDoc** at `/redoc`
- Both generated automatically from your code!
## Let's Build Something Real
### Installation
```bash
pip install fastapi uvicorn
```
### Basic Example - E-commerce API
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from uuid import UUID, uuid4
app = FastAPI(title="E-Commerce API", version="1.0.0")
# Data models
class Product(BaseModel):
id: UUID
name: str
price: float
in_stock: bool = True
class CreateProductRequest(BaseModel):
name: str
price: float
in_stock: bool = True
# In-memory "database"
products: List[Product] = []
# Routes
@app.get("/")
async def root():
return {"message": "Welcome to our E-Commerce API!"}
@app.get("/products", response_model=List[Product])
async def get_products():
return products
@app.get("/products/{product_id}")
async def get_product(product_id: UUID):
for product in products:
if product.id == product_id:
return product
raise HTTPException(status_code=404, detail="Product not found")
@app.post("/products", response_model=Product)
async def create_product(product_request: CreateProductRequest):
product = Product(
id=uuid4(),
name=product_request.name,
price=product_request.price,
in_stock=product_request.in_stock
)
products.append(product)
return product
@app.put("/products/{product_id}")
async def update_product(product_id: UUID, updated_product: CreateProductRequest):
for idx, product in enumerate(products):
if product.id == product_id:
products[idx] = Product(
id=product_id,
name=updated_product.name,
price=updated_product.price,
in_stock=updated_product.in_stock
)
return products[idx]
raise HTTPException(status_code=404, detail="Product not found")
@app.delete("/products/{product_id}")
async def delete_product(product_id: UUID):
for idx, product in enumerate(products):
if product.id == product_id:
return products.pop(idx)
raise HTTPException(status_code=404, detail="Product not found")
```
### Running the Server
```bash
uvicorn main:app --reload
```
Visit:
- **API**: http://localhost:8000
- **Docs**: http://localhost:8000/docs
- **Alternative Docs**: http://localhost:8000/redoc
## Advanced Features
### Query Parameters & Validation
```python
from fastapi import Query
@app.get("/products/")
async def search_products(
name: Optional[str] = Query(None, min_length=2, max_length=50),
min_price: Optional[float] = Query(0, ge=0),
max_price: Optional[float] = Query(1000, le=10000),
in_stock: bool = True
):
# Your filtering logic here
return {"filters": {"name": name, "min_price": min_price}}
```
### Dependency Injection
```python
from fastapi import Depends
async def get_database():
# Simulate database connection
return {"db": "connected"}
@app.get("/users/")
async def read_users(db: dict = Depends(get_database)):
return {"users": ["Alice", "Bob"], "database_status": db}
```
### Background Tasks
```python
from fastapi import BackgroundTasks
def send_order_confirmation_email(order_id: UUID):
# Simulate email sending
print(f"Sent confirmation for order {order_id}")
@app.post("/orders/")
async def create_order(
background_tasks: BackgroundTasks,
product_id: UUID
):
order_id = uuid4()
background_tasks.add_task(send_order_confirmation_email, order_id)
return {"order_id": order_id, "status": "created"}
```
## Real-World Project Structure
```
my_ecommerce_api/
├── main.py
├── routers/
│ ├── products.py
│ ├── users.py
│ └── orders.py
├── models/
│ ├── product.py
│ └── user.py
├── dependencies.py
└── database.py
```
## Why Developers Love FastAPI
### ✅ **Advantages**
- **Rapid Development**: Write less code, get more features
- **Fewer Bugs**: Type checking catches errors early
- **Great Editor Support**: Autocompletion everywhere
- **Modern Python**: Uses latest Python features
- **Easy to Learn**: Intuitive and well-documented
### 🎯 **Perfect Use Cases**
- RESTful APIs
- Microservices
- Internal tools
- Prototyping
- Machine Learning APIs
## Performance Comparison
```
Framework Requests/sec
FastAPI ~10,000
Flask ~2,000
Django ~1,500
Node.js Express ~8,000
```
## Quick Tips for Success
1. **Use type hints religiously** - they're your superpower
2. **Leverage automatic docs** - your API is self-documenting
3. **Use dependencies** for database connections, authentication
4. **Test with the built-in TestClient**
5. **Deploy with Uvicorn** in production
## Example: Testing Your API
```python
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_product():
response = client.post(
"/products/",
json={"name": "Laptop", "price": 999.99}
)
assert response.status_code == 200
assert response.json()["name"] == "Laptop"
```
FastAPI feels like magic because it turns Python's type hints into a powerful development experience. You get validation, serialization, documentation, and editor support almost for free!
The framework is particularly excellent for:
- Building production-ready APIs quickly
- Teams that want maintainable, self-documenting code
- Projects that need high performance
- Developers who love modern Python features