Skip to content

Emeteil/fastapi_template

Repository files navigation

FastAPI Project Template

A professional, high-performance, and feature-rich FastAPI project template designed for scalability and ease of use. This template follows best practices for API design, documentation, and security.

Branches

This repository is organized into three main branches to suit different project needs:

  1. main: The base version. Includes full authorization (JWT, Login, Registration) and standard API patterns. No WebSocket support.
  2. with-websockets: Extends main by adding a robust WebSocket system with connection management, rooms/groups support, and real-time broadcasting.
  3. without-authorization: A lightweight, stripped-down version. All authentication-related logic, files, and dependencies have been removed. Ideal for public-facing utilities or internal tools.

Project Structure

├── api/                    # API route definitions
│   ├── schemas/            # Pydantic models for requests and responses
│   ├── admin.py            # Service and administrative endpoints
│   ├── authorization.py    # Authentication endpoints (Login, Register)
│   └── websockets.py       # WebSocket handlers (only in with-websockets branch)
├── database/               # Data persistence (JSON files by default)
├── static/                 # Static assets (CSS, JS, Images)
├── templates/              # HTML templates (Jinja2)
├── utils/                  # Core utilities and helpers
│   ├── db/                 # Database interaction logic
│   ├── validation/         # Data validation logic
│   ├── api_models.py       # Global Pydantic models for API standards
│   ├── api_response.py     # Standardized JSON response helper
│   └── status_codes.py     # Map of HTTP status codes and descriptions
├── authorization.py        # Authentication dependencies and JWT logic
├── events.py               # Global exception handlers and error pages
├── main.py                 # Application entry point and metadata
├── settings.py             # FastAPI app initialization and middleware
└── settings.yml            # Main configuration file

Development Standards

1. API Response Standard

All API responses follow a strict format to ensure frontend consistency. Use the apiResponse helper from utils/api_response.py.

Success Response

{
  "status": "success",
  "data": {
    "message": "Pong!",
    "user_id": "123"
  }
}

Error Response

{
  "status": "error",
  "error": {
    "code": 401,
    "message": "Unauthorized",
    "details": "Invalid or expired token"
  }
}

2. Pydantic Models & Generics

Models are defined in api/schemas/. To ensure perfect documentation in Swagger UI, we use Generics.

Example: Create a schema in api/schemas/your_module.py:

from pydantic import BaseModel

class MyData(BaseModel):
    id: int
    name: str

Then use it in your route with ApiResponse[T]:

from utils.api_models import ApiResponse
from api.schemas.your_module import MyData

@router.get("/data", response_model=ApiResponse[MyData])
async def get_data():
    return apiResponse({"id": 1, "name": "Test"})

3. Documentation (OpenAPI)

FastAPI automatically generates documentation at /docs (Swagger UI).

  • Tags: Group routes using tags=["Name"] in APIRouter.
  • Summaries/Descriptions: Adding these decorators to functions makes the documentation readable.
  • Security: Specific routes are marked as protected using Depends(login_required_cookies).

4. Authentication

Authentication is handled via JWT tokens stored in HTTP-only cookies.

  • Use is_logged for optional checks.
  • Use login_required_cookies as a dependency for mandatory protection.
  • The Authorization header (Bearer <token>) is also supported for mobile or external API clients.

5. CORS Support

CORS is pre-configured in settings.py and can be easily adjusted via settings.yml:

cors:
  allow_origins: ["*"]
  allow_credentials: true
  allow_methods: ["*"]
  allow_headers: ["*"]

How to Create New Features

  1. Define Schema: Create a Pydantic model in api/schemas/.
  2. Create Routes: Add a new .py file in api/ (or update an existing one).
  3. Register Router: Import and include the router in main.py.
  4. Implement Logic: Use utils/ for validation and database operations.
  5. Standardize Output: Always wrap your returns in apiResponse().

Getting Started

  1. Install dependencies:
    pip install -r requirements.txt
  2. Configure settings in settings.yml.
  3. Run the application:
    python main.py
  4. Access documentation at http://localhost:80/docs.

About

High-performance FastAPI project template.

Topics

Resources

Stars

Watchers

Forks

Contributors