Learn FASTAPI with Real Code Examples
Updated Nov 25, 2025
Code Sample Descriptions
1
FastAPI Simple Counter API
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class CounterResponse(BaseModel):
count: int
count = 0
@app.get('/counter', response_model=CounterResponse)
async def get_counter():
return { 'count': count }
@app.post('/counter/increment', response_model=CounterResponse)
async def increment_counter():
global count
count += 1
return { 'count': count }
@app.post('/counter/decrement', response_model=CounterResponse)
async def decrement_counter():
global count
count -= 1
return { 'count': count }
@app.post('/counter/reset', response_model=CounterResponse)
async def reset_counter():
global count
count = 0
return { 'count': count }
# Run with: uvicorn main:app --reload
Demonstrates a simple FastAPI REST API with a counter using async routes and Pydantic models.
2
FastAPI Item CRUD
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
items = {}
@app.post('/items/{item_id}')
async def create_item(item_id: int, item: Item):
items[item_id] = item
return item
@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.put('/items/{item_id}')
async def update_item(item_id: int, item: Item):
items[item_id] = item
return item
@app.delete('/items/{item_id}')
async def delete_item(item_id: int):
return items.pop(item_id, None)
Basic CRUD for items using FastAPI and in-memory storage.
3
FastAPI Query Parameters Example
from fastapi import FastAPI
app = FastAPI()
@app.get('/search')
async def search(q: str = '', limit: int = 10):
return { 'query': q, 'limit': limit }
Use query parameters to filter results in FastAPI.
4
FastAPI Path Parameters Example
from fastapi import FastAPI
app = FastAPI()
@app.get('/users/{user_id}')
async def get_user(user_id: int):
return { 'user_id': user_id }
Use path parameters to identify resources.
5
FastAPI Optional Parameters Example
from fastapi import FastAPI
from typing import Optional
app = FastAPI()
@app.get('/items/')
async def read_items(skip: int = 0, limit: Optional[int] = None):
return { 'skip': skip, 'limit': limit }
Demonstrates optional query parameters in FastAPI.
6
FastAPI Request Body Example
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
email: str
@app.post('/users/')
async def create_user(user: User):
return user
Accept a JSON body in POST requests.
7
FastAPI Response Model Example
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserOut(BaseModel):
username: str
@app.get('/user/{user_id}', response_model=UserOut)
async def get_user(user_id: int):
return { 'username': f'user{user_id}', 'password': 'secret' }
Use Pydantic models to control response data.
8
FastAPI Dependency Injection Example
from fastapi import FastAPI, Depends
app = FastAPI()
def common_query(q: str = None):
return q
@app.get('/items/')
async def read_items(q: str = Depends(common_query)):
return { 'q': q }
Use dependencies to share logic between endpoints.
9
FastAPI Background Tasks Example
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(message: str):
with open('log.txt', 'a') as f:
f.write(message + '\n')
@app.post('/send/')
async def send_message(message: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, message)
return { 'message': message }
Run background tasks after returning a response.
10
FastAPI File Upload Example
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post('/upload/')
async def upload_file(file: UploadFile = File(...)):
content = await file.read()
return { 'filename': file.filename, 'size': len(content) }
Accept file uploads in a FastAPI endpoint.