Learn Fastapi - 10 Code Examples & CST Typing Practice Test
FastAPI is a modern, high-performance Python web framework for building APIs with automatic interactive documentation. It emphasizes speed, type hints, and ease of development, leveraging Python 3.7+ features.
View all 10 Fastapi code examples →
Learn FASTAPI with Real Code Examples
Updated Nov 25, 2025
Code Sample Descriptions
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Frequently Asked Questions about Fastapi
What is Fastapi?
FastAPI is a modern, high-performance Python web framework for building APIs with automatic interactive documentation. It emphasizes speed, type hints, and ease of development, leveraging Python 3.7+ features.
What are the primary use cases for Fastapi?
Building RESTful and JSON APIs. High-performance asynchronous backend. Microservices architecture. Data validation and processing APIs. Integrating with frontend frameworks or machine learning models
What are the strengths of Fastapi?
Very fast due to Starlette and Pydantic under the hood. Automatic docs reduce boilerplate. Strong Python type checking. Easy to integrate with async DB and external APIs. Extensible and modular via dependencies and routers
What are the limitations of Fastapi?
Relatively new ecosystem compared to Django/Flask. Learning curve for async programming and dependencies. Less mature for server-side rendering. Requires understanding of Pydantic models. Complex projects may need careful organization to avoid spaghetti
How can I practice Fastapi typing speed?
CodeSpeedTest offers 10+ real Fastapi code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.