Introduction to FastAPI 🚀
FastAPI is a modern, fast (high-performance) web framework for building APIs with Python. It is based on Starlette (for web handling) and Pydantic (for data validation). It is known for its speed, automatic OpenAPI documentation, and easy data validation.
🌟 Key Features of FastAPI
✅ Blazing Fast: Comparable to Node.js & Go (thanks to Starlette & Pydantic).
✅ Automatic API Documentation: Comes with Swagger UI (/docs) & ReDoc (/redoc).
✅ Built-in Data Validation: Uses Pydantic for request & response validation.
✅ Asynchronous Support: Built-in support for async and await.
✅ Dependency Injection: Easy-to-use dependency injection system.
✅ Security: Provides built-in authentication & authorization mechanisms.
🔧 Installing FastAPI
Before you start, install FastAPI and Uvicorn (ASGI server):
pip install fastapi uvicorn
🚀 Creating Your First FastAPI App
Let's build a simple Hello, World! API.
📌 Code: FastAPI Basic Example
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def home():
return {"message": "Hello, World!"}
# Run the app using: uvicorn main:app --reload
How to Run the FastAPI App
Save the file as main.py and start the server:
uvicorn main:app --reload
Now, visit:
📌 Swagger UI → http://127.0.0.1:8000/docs
📌 ReDoc UI → http://127.0.0.1:8000/redoc
📌 Creating RESTful API Endpoints
FastAPI supports GET, POST, PUT, DELETE methods.
✅ Example: Handling API Requests
from fastapi import FastAPI
app = FastAPI()
# GET request
@app.get("/items/{item_id}")
async def get_item(item_id: int):
return {"item_id": item_id, "message": "Item retrieved"}
# POST request
@app.post("/items/")
async def create_item(item: dict):
return {"message": "Item created", "item": item}
📌 Test it using Swagger UI: http://127.0.0.1:8000/docs
📌 Using Pydantic for Data Validation
FastAPI uses Pydantic models for automatic data validation.
✅ Example: Validating User Data
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
# Pydantic Model
class User(BaseModel):
id: int
name: str
email: EmailStr
# POST request with validation
@app.post("/users/")
async def create_user(user: User):
return {"message": "User created", "user": user}
📌 Request Body (JSON):
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
🚫 If an invalid email is provided, FastAPI automatically returns an error.
📌 Query Parameters and Path Variables
FastAPI supports query parameters and path variables.
✅ Example: Using Query Parameters
@app.get("/search/")
async def search_items(q: str, limit: int = 10):
return {"query": q, "limit": limit}
👉 Example Request:
GET /search/?q=fastapi&limit=5
👉 Response:
{
"query": "fastapi",
"limit": 5
}
📌 Handling Request Headers & Form Data
FastAPI can extract headers, form data, and cookies.
✅ Example: Getting Headers
from fastapi import Request
@app.get("/headers/")
async def read_headers(request: Request):
return {"user-agent": request.headers.get("user-agent")}
✅ Example: Handling Form Data
from fastapi import Form
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"message": f"User {username} logged in"}
📌 Send a form request (not JSON) with username and password.
📌 FastAPI with Database (SQLAlchemy)
FastAPI integrates well with databases like PostgreSQL, MySQL, SQLite using SQLAlchemy.
✅ Example: FastAPI + SQLite (SQLAlchemy)
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from database import SessionLocal, engine, Base
from models import User
app = FastAPI()
# Dependency to get the database session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/")
async def get_users(db: Session = Depends(get_db)):
users = db.query(User).all()
return users
📌 Database connection and models would be defined in separate files (database.py & models.py).
📌 Authentication with FastAPI
FastAPI supports authentication methods like:
- OAuth2
- JWT (JSON Web Tokens)
- API Key-based Authentication
✅ Example: OAuth2 with JWT
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/protected/")
async def protected_route(token: str = Depends(oauth2_scheme)):
return {"message": "You are authenticated", "token": token}
Now, you must pass a valid token to access /protected/.
📌 FastAPI WebSockets (Real-time Communication)
FastAPI supports WebSockets for real-time communication.
✅ Example: WebSocket Echo Server
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"You sent: {data}")
Use WebSockets for real-time chat apps, stock price updates, etc..
📌 Automatic API Documentation
FastAPI automatically generates API docs.
- 📌 Swagger UI → http://127.0.0.1:8000/docs
- 📌 ReDoc UI → http://127.0.0.1:8000/redoc
👉 No extra configuration is needed!
🎯 Conclusion
FastAPI is a powerful yet simple framework that makes building APIs fast and efficient.
💡 Why Choose FastAPI?
✅ Fast performance (near Go & Node.js speed)
✅ Automatic request validation & documentation
✅ Asynchronous support (async/await)
✅ Easy database & authentication integration
Comments
Post a Comment