
FastAPI
Every API interaction involves a request (from client) and response (from server). Understanding this flow is essential.
Client Server
| |
|-------- HTTP Request ----------> |
| (data to send) |
| |
| (Processing)
| |
| <------ HTTP Response ----------- |
| (data returned) |
| |A request includes:
# Example request structure
POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"name": "John",
"email": "john@example.com"
}from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
email: str
@app.post("/users")
async def create_user(user: User):
# FastAPI automatically:
# 1. Parses JSON from request body
# 2. Validates it matches User model
# 3. Passes as 'user' parameter
return {"id": 1, **user.dict()}A response includes:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def get_item(item_id: int):
# Returns 200 status by default
# Converts dict to JSON automatically
return {"id": item_id, "name": "Item"}from fastapi import Header
from typing import Optional
@app.get("/data")
async def get_data(
user_agent: Optional[str] = Header(None),
accept_language: Optional[str] = Header(None)
):
# Access HTTP headers
return {
"user_agent": user_agent,
"accept_language": accept_language
}from fastapi import status
@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(user: dict):
# Returns 201 Created instead of default 200
return user
@app.get("/items/{item_id}")
async def get_item(item_id: int):
if not item:
return {"error": "Not found"} # Still 200
return itemfrom pydantic import BaseModel
class Product(BaseModel):
name: str
price: float
@app.post("/products")
async def create_product(product: Product):
# Request: {
# "name": "Laptop",
# "price": 999.99
# }
#
# Response: {
# "id": 1,
# "name": "Laptop",
# "price": 999.99,
# "created": "2024-03-02"
# }
return {
"id": 1,
**product.dict(),
"created": "2024-03-02"
}Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward