Sufast/Documentation
Examples
Code Examples
Real-world examples and tutorials to help you build amazing applications with Sufast.
Basic API Server
Simple REST API with CRUD operations
Learn the fundamentals by building a complete REST API with users, posts, and comments.
View ExampleAuthentication System
JWT authentication with role-based access
Implement secure authentication with JWT tokens, password hashing, and protected routes.
View ExampleDatabase Integration
PostgreSQL with async connection pooling
Connect to PostgreSQL with async/await, connection pooling, and database migrations.
View ExampleMore Examples
File uploads, WebSockets, and advanced patterns
Explore advanced use cases including real-time features and file handling.
Coming SoonHello World Example
The simplest possible Sufast application
hello_world.pypython
from sufast import App
# Create the application
app = App()
# Define a simple route
@app.get("/")
def hello_world():
return {"message": "Hello, World! π"}
# Add a health check endpoint
@app.get("/health")
def health_check():
return {"status": "healthy", "framework": "Sufast"}
# Run the application
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)Running the Example
Terminalbash
# Save the code as hello_world.py
python hello_world.py
# Test the endpoints
curl http://localhost:8080/
curl http://localhost:8080/healthPath Parameters Example
Working with dynamic URL paths
path_params.pypython
from sufast import App
app = App()
# Simple path parameter
@app.get("/users/{user_id}")
def get_user(user_id: str):
return {"user_id": user_id, "name": f"User {user_id}"}
# Multiple path parameters
@app.get("/users/{user_id}/posts/{post_id}")
def get_user_post(user_id: str, post_id: str):
return {
"user_id": user_id,
"post_id": post_id,
"title": f"Post {post_id} by User {user_id}"
}
# Type conversion
@app.get("/items/{item_id}")
def get_item(item_id: int): # Automatically converts to int
return {
"item_id": item_id,
"type": type(item_id).__name__,
"price": item_id * 10.99
}
# Path with file extension
@app.get("/files/{file_path:path}")
def get_file(file_path: str):
return {
"file_path": file_path,
"extension": file_path.split(".")[-1] if "." in file_path else None
}
if __name__ == "__main__":
app.run()Query Parameters Example
Handling URL query strings and filters
query_params.pypython
from sufast import App
from typing import Optional, List
app = App()
# Basic query parameters with defaults
@app.get("/search")
def search(q: str, limit: int = 10, offset: int = 0):
return {
"query": q,
"limit": limit,
"offset": offset,
"results": [f"Result {i}" for i in range(offset, offset + limit)]
}
# Optional parameters
@app.get("/products")
def get_products(
category: Optional[str] = None,
min_price: Optional[float] = None,
max_price: Optional[float] = None,
in_stock: bool = True
):
filters = {
"category": category,
"min_price": min_price,
"max_price": max_price,
"in_stock": in_stock
}
# Remove None values
filters = {k: v for k, v in filters.items() if v is not None}
return {
"filters": filters,
"products": ["Product A", "Product B", "Product C"]
}
# List parameters (tags=python&tags=web&tags=api)
@app.get("/articles")
def get_articles(tags: List[str] = [], sort: str = "date"):
return {
"tags": tags,
"sort": sort,
"articles": [
{"title": "Article 1", "tags": tags[:2]},
{"title": "Article 2", "tags": tags[1:]}
]
}
# Complex filtering
@app.get("/users")
def list_users(
page: int = 1,
size: int = 20,
search: Optional[str] = None,
role: Optional[str] = None,
active: Optional[bool] = None,
sort_by: str = "created_at",
sort_order: str = "desc"
):
# Validate parameters
if page < 1:
return {"error": "Page must be >= 1"}, 400
if size < 1 or size > 100:
return {"error": "Size must be between 1 and 100"}, 400
if sort_order not in ["asc", "desc"]:
return {"error": "Sort order must be 'asc' or 'desc'"}, 400
return {
"pagination": {"page": page, "size": size},
"filters": {
"search": search,
"role": role,
"active": active
},
"sorting": {"by": sort_by, "order": sort_order},
"users": [
{"id": 1, "name": "Alice", "role": "admin", "active": True},
{"id": 2, "name": "Bob", "role": "user", "active": True}
]
}
if __name__ == "__main__":
app.run()Request Body Example
Handling JSON and form data
request_body.pypython
from sufast import App, Request
import json
app = App()
# JSON request body
@app.post("/users")
async def create_user(request: Request):
try:
data = await request.json()
except json.JSONDecodeError:
return {"error": "Invalid JSON format"}, 400
# Validate required fields
required_fields = ["name", "email"]
missing = [field for field in required_fields if field not in data]
if missing:
return {"error": f"Missing fields: {', '.join(missing)}"}, 400
# Create user (mock)
user = {
"id": 123,
"name": data["name"],
"email": data["email"],
"age": data.get("age"),
"created_at": "2024-01-01T00:00:00Z"
}
return {"user": user}, 201
# Form data
@app.post("/contact")
async def contact_form(request: Request):
form = await request.form()
name = form.get("name")
email = form.get("email")
message = form.get("message")
if not all([name, email, message]):
return {"error": "All fields are required"}, 400
return {
"message": "Contact form submitted successfully",
"data": {
"name": name,
"email": email,
"message_length": len(message)
}
}
# File upload
@app.post("/upload")
async def upload_file(request: Request):
form = await request.form()
file = form.get("file")
if not file or not file.filename:
return {"error": "No file provided"}, 400
# Read file content
content = await file.read()
return {
"filename": file.filename,
"content_type": file.content_type,
"size": len(content),
"message": "File uploaded successfully"
}
# Raw body
@app.post("/webhook")
async def webhook(request: Request):
# Get raw body as bytes
body = await request.body()
# Get headers
signature = request.headers.get("x-signature")
content_type = request.headers.get("content-type")
return {
"body_size": len(body),
"content_type": content_type,
"has_signature": signature is not None,
"message": "Webhook received"
}
if __name__ == "__main__":
app.run()π Ready for More?
Explore advanced examples and real-world applications