Building REST APIs is one of the most in-demand skills in web development. In this guide, I'll show you how to build a production-ready REST API with Python and FastAPI in under 10 minutes.
Why FastAPI?
FastAPI is the fastest-growing Python web framework because it's:
- Fast: One of the fastest Python frameworks available
- Easy: Automatic API documentation with Swagger UI
- Modern: Built with Python type hints for better code quality
- Production-ready: Used by major companies like Netflix, Uber, and Microsoft
Step 1: Install FastAPI
pip install fastapi uvicorn python-multipart
Step 2: Create Your First API
Create a file called main.py:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI(title="My REST API", version="1.0.0")
# Data model
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
# In-memory storage (use a database in production)
items = {}
@app.get("/")
def root():
return {"message": "Welcome to My REST API"}
@app.get("/items")
def get_items():
return {"items": list(items.values())}
@app.get("/items/{item_id}")
def get_item(item_id: int):
if item_id not in items:
return {"error": "Item not found"}, 404
return items[item_id]
@app.post("/items/{item_id}")
def create_item(item_id: int, item: Item):
items[item_id] = item.dict()
return {"message": "Item created", "item": item}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
if item_id not in items:
return {"error": "Item not found"}, 404
items[item_id] = item.dict()
return {"message": "Item updated", "item": item}
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
if item_id not in items:
return {"error": "Item not found"}, 404
del items[item_id]
return {"message": "Item deleted"}
Step 3: Run Your API
uvicorn main:app --reload
Your API is now running at http://localhost:8000!
Visit http://localhost:8000/docs for the automatic Swagger UI documentation.
Step 4: Add Authentication
For production APIs, always add authentication:
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
token = credentials.credentials
if token != "your-secret-token":
raise HTTPException(status_code=401, detail="Invalid token")
return token
@app.get("/protected")
def protected_route(token: str = Depends(verify_token)):
return {"message": "You have access!", "token": token}
Step 5: Deploy to Production
The easiest way to deploy FastAPI is with Docker:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Best Practices for REST APIs
- Use proper HTTP status codes (200, 201, 400, 401, 404, 500)
-
Version your API (
/api/v1/items) - Validate all inputs with Pydantic models
- Add rate limiting to prevent abuse
- Document with OpenAPI (FastAPI does this automatically!)
- Use environment variables for secrets and configuration
Need a Custom REST API Built for You?
If you need a professional REST API built for your project — whether it's a mobile app backend, data processing pipeline, or third-party integration — I can help!
Check out my Fiverr gig:
- 🔌 Professional REST API Development — Starting from $20
I build clean, documented, production-ready APIs with full testing and deployment support!
Questions about building REST APIs? Drop a comment below!
Top comments (0)