โก FastAPI Quick Start Guide
Build Your First API in 5 Minutes!
1
Install FastAPI & Uvicorn
First, install FastAPI (the framework) and Uvicorn (the server that runs it).
$ pip install fastapi uvicorn
$ pip install python-multipart
๐ก Pro Tip
Create a virtual environment first to keep your project dependencies isolated:
$ python -m venv venv
$ source venv/bin/activate
$ pip install fastapi uvicorn
2
Create Your First API
Create a file called main.py with this code:
main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
โ
That's It!
You just created a fully functional API with automatic documentation in less than 15 lines of code!
3
Run Your API Server
Start the server using Uvicorn:
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000
INFO: Application startup complete.
What does --reload do?
--reload automatically restarts the server when you change code. Perfect for development! Remove it in production.
4
Test Your API - 3 Ways!
Method 1: Interactive Docs (Recommended!)
FastAPI automatically generates beautiful interactive documentation!
Open your browser and visit:
๐ http://127.0.0.1:8000/docs (Swagger UI - Interactive)
๐ http://127.0.0.1:8000/redoc (ReDoc - Clean documentation)
๐ผ๏ธ At /docs you'll see:
โข All your endpoints listed
โข Try it out buttons to test each endpoint
โข Automatic request/response examples
โข Schema definitions
Method 2: Browser
Visit: http://127.0.0.1:8000/
You'll see: {"message": "Hello World"}
Method 3: Curl (Command Line)
$ curl http://127.0.0.1:8000/
{"message": "Hello World"}
$ curl http://127.0.0.1:8000/items/42
{"item_id": 42}
5
Add Data Validation with Pydantic
Pydantic models automatically validate incoming data:
main.py
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.post("/items/")
async def create_item(item: Item):
return {
"name": item.name,
"price": item.price,
"total": item.price + (item.tax or 0)
}
โ
Automatic Validation!
FastAPI will automatically:
- โ Validate that
name is a string
- โ Validate that
price is a number
- โ Return 422 error if validation fails
- โ Generate JSON schema in docs
6
Use All HTTP Methods
main.py
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return items[item_id]
@app.post("/items/")
async def create_item(item: Item):
item_id = len(items) + 1
items[item_id] = item
return {"id": item_id, "item": item}
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
items[item_id] = item
return {"updated": True, "item": item}
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
del items[item_id]
return {"deleted": True}
๐ Why FastAPI is Amazing
โก
Blazing Fast
One of the fastest Python frameworks. Performance comparable to Node.js and Go.
๐
Auto Documentation
Interactive API docs generated automatically. Test endpoints directly in your browser!
โ
Auto Validation
Pydantic validates all inputs automatically. Catch errors before they happen.
๐ฏ
Type Hints
Use Python type hints for better IDE support, auto-completion, and fewer bugs.
๐
Security
Built-in support for OAuth2, JWT, API keys, and more authentication methods.
๐งช
Easy Testing
Simple to test with pytest. TestClient makes API testing straightforward.
7
Common FastAPI Patterns
Query Parameters
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return items[skip : skip + limit]
Path + Query Parameters
@app.get("/users/{user_id}/items")
async def read_user_items(
user_id: int,
skip: int = 0,
limit: int = 10
):
return {"user_id": user_id, "items": items[skip:skip+limit]}
Status Codes
from fastapi import status
@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
return item
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int):
pass
Response Models
class UserIn(BaseModel):
username: str
password: str
class UserOut(BaseModel):
username: str
@app.post("/users/", response_model=UserOut)
async def create_user(user: UserIn):
return user
FastAPI vs Flask vs Django
| Feature |
FastAPI |
Flask |
Django |
| Performance |
โกโกโก Extremely Fast |
โกโก Moderate |
โก Slower |
| Auto Docs |
โ
Built-in (Swagger/ReDoc) |
โ Manual |
โ Manual |
| Data Validation |
โ
Automatic (Pydantic) |
โ Manual |
โ
With DRF |
| Async Support |
โ
Native |
โ ๏ธ Limited |
โ
Added in 3.1+ |
| Learning Curve |
Easy |
Easy |
Steep |
| Best For |
APIs, ML models, microservices |
Simple web apps |
Full web applications |
โ ๏ธ Common Issues & Solutions
Issue: "Address already in use"
โ Another app is using port 8000. Use: uvicorn main:app --port 8001
Issue: Changes not showing up
โ Make sure you're using --reload flag
Issue: Import errors
โ Check your virtual environment is activated and packages are installed
Issue: 404 Not Found on /docs
โ Make sure server is running on correct port (check terminal output)
๐ฏ Next Steps: Level Up Your API
- Add authentication with JWT tokens
- Connect to a real database (PostgreSQL, MongoDB)
- Implement CORS for frontend access
- Add rate limiting to prevent abuse
- Write comprehensive tests with pytest
- Deploy to production (Heroku, AWS, Railway)
- Add monitoring and logging
- Integrate your W4D1 design patterns
- Build ML model serving endpoints
- Create API versioning strategy