Built-in Features
Overview
Section titled “Overview”Zenith provides convenient methods to quickly add common features to your application. These methods give you working implementations that you can customize as needed.
Authentication
Section titled “Authentication”Add JWT authentication to your application:
from zenith import Zenith
app = Zenith()
# Add authentication systemapp.add_auth()
# This creates:# - POST /auth/login endpoint for token generation# - JWT token validation infrastructure# - Authentication middleware for protected routes# - Configurable token expirationUsing Authentication
Section titled “Using Authentication”from zenith import Auth
@app.get("/protected")async def protected_route(user=Auth): """This route requires authentication.""" return {"message": "You are authenticated", "user_id": user.id}
@app.get("/public")async def public_route(): """This route is publicly accessible.""" return {"message": "Anyone can access this"}Login Flow
Section titled “Login Flow”# Your users can authenticate:# POST /auth/login# Body: {"username": "alice", "password": "secret123"}# Response: {"access_token": "eyJ...", "token_type": "bearer"}
# Then use the token:# GET /protected# Headers: {"Authorization": "Bearer eyJ..."}Admin Panel
Section titled “Admin Panel”Add an admin dashboard to monitor your application:
# Add admin panel with default pathapp.add_admin() # Available at /admin
# Or specify a custom pathapp.add_admin("/dashboard") # Available at /dashboardAdmin Features
Section titled “Admin Features”The admin panel provides:
- System health monitoring at
/admin/health - Application statistics at
/admin/stats - Recent logs viewer at
/admin/logs - Basic metrics dashboard at
/admin
# Complete example with admin panelapp = Zenith()app.add_admin()
# The admin endpoints are now available:# GET /admin - Dashboard overview# GET /admin/health - System health status# GET /admin/stats - Application statistics# GET /admin/logs - Recent application logsAPI Documentation
Section titled “API Documentation”Generate interactive API documentation automatically:
# Add OpenAPI documentationapp.add_api("My API", "1.0.0", "API for my application")
# This creates:# - GET /docs - Interactive Swagger UI# - GET /redoc - Alternative ReDoc interface# - GET /openapi.json - OpenAPI schemaDocumentation Features
Section titled “Documentation Features”Your API documentation includes:
- Interactive testing - Try endpoints directly from the browser
- Request/response schemas - Automatic from your Pydantic models
- Authentication testing - Test protected endpoints
- Code examples - Multiple programming languages
- Export capability - Download OpenAPI spec for Postman/Insomnia
Automatic Documentation
Section titled “Automatic Documentation”from pydantic import BaseModel
class UserCreate(BaseModel): """Schema for creating a user.""" name: str email: str age: int
@app.post("/users", response_model=User)async def create_user(user: UserCreate): """ Create a new user.
This docstring becomes the endpoint description in the docs! The UserCreate model is automatically documented with examples. """ return await User.create(**user.model_dump())
# This endpoint appears in /docs with:# - Full schema documentation# - Try-it-out functionality# - Example requests and responsesCombining Features
Section titled “Combining Features”Chain methods together for a complete setup:
from zenith import Zenith
# Configure everything at onceapp = (Zenith() .add_auth() # Authentication system .add_admin("/dashboard") # Admin panel .add_api("My API", "1.0.0")) # API documentation
# Your application now has:# - JWT authentication at /auth/login# - Protected route support with Auth dependency# - Admin dashboard at /dashboard# - Interactive API docs at /docs and /redoc
# Add your business logic@app.get("/users")async def list_users(user=Auth): """List all users (requires authentication).""" return await User.all()
@app.get("/status")async def status(): """Public status endpoint.""" return {"status": "operational"}Customization
Section titled “Customization”All features can be customized:
# Custom authentication settingsapp.add_auth( secret_key="your-secret-key", algorithm="RS256", expire_minutes=60)
# Custom admin configurationapp.add_admin( path="/admin", title="MyApp Admin", enable_metrics=True)
# Custom API documentationapp.add_api( title="My API", version="2.0.0", description="Production API", terms_of_service="https://example.com/terms", contact={"email": "api@example.com"})Complete Example
Section titled “Complete Example”Here’s a working application using these features:
from zenith import Zenithfrom zenith import Authfrom zenith.db import ZenithModelfrom sqlmodel import Fieldfrom datetime import datetimefrom typing import Optional
# Create app with featuresapp = (Zenith() .add_auth() .add_admin() .add_api("Feature Demo", "1.0.0"))
# Define a modelclass Task(ZenithModel, table=True): id: Optional[int] = Field(primary_key=True) title: str completed: bool = Field(default=False) user_id: int created_at: datetime = Field(default_factory=datetime.now)
@app.get("/")async def home(): """API information endpoint.""" return { "name": "Zenith Feature Demo", "version": "1.0.0", "docs": "/docs", "admin": "/admin", "login": "/auth/login" }
@app.get("/tasks")async def list_tasks(user=Auth): """List tasks for authenticated user.""" tasks = await Task.where(user_id=user.id).all() return {"tasks": [t.model_dump() for t in tasks]}
@app.post("/tasks")async def create_task(title: str, user=Auth): """Create a new task.""" task = await Task.create(title=title, user_id=user.id) return {"task": task.model_dump()}
if __name__ == "__main__": import uvicorn print("🚀 Feature Demo Running") print("📝 API Docs: http://localhost:8004/docs") print("🔧 Admin Panel: http://localhost:8004/admin") print("🔐 Login: POST http://localhost:8004/auth/login") uvicorn.run(app, host="0.0.0.0", port=8004)Run the example:
python examples/04-one-liner-features.pyThen visit:
http://localhost:8004/docs- Interactive API documentationhttp://localhost:8004/admin- Admin dashboardhttp://localhost:8004/auth/login- Authentication endpoint
These convenience methods help you get started quickly while maintaining flexibility to customize and extend as your application grows.