Skip to content

reze-dev/PyGenesis

Repository files navigation

PyGenesis ⚛️

PyGenesis is a production-ready, feature-complete FastAPI template designed for building scalable backend applications. It provides reproducible system environment setups, container orchestration, token-based authentication, database persistence, and automated code styling tools out of the box.


✨ Features

  • 🛠️ Reproducible Environments: Powered by Nix Flakes and direnv to guarantee that every developer uses the exact same Python version (3.11), compiler toolchains, and CLI utilities.
  • Next-Gen Python Tooling: Uses UV (a blisteringly fast package installer and resolver written in Rust) for virtual environments and lockfile management.
  • 🔐 JWT Authentication & Security:
    • Complete OAuth2 password flow.
    • Password hashing using bcrypt.
    • Signed JSON Web Token (JWT) creation and validation using pyjwt.
    • Injectable auth guards (get_current_user) to secure API endpoints.
  • 🗄️ SQLAlchemy & Alembic Persistence:
    • Declarative base setup with dynamic connection string loading via Pydantic.
    • Pre-defined User database model.
    • Auto-generating migration schemas using Alembic revisions.
    • Automated local DB table setup on application startup.
  • 🐳 Docker-Compose Ready:
    • Multi-container setup containing the FastAPI web application and a PostgreSQL database.
    • Production-ready, multi-stage building Dockerfile.
  • 🧪 Robust Testing Suite:
    • Integration tests covering auth, user registration, and profile endpoints.
    • Clean transaction rollback testing using an in-memory SQLite database (conftest.py).
  • 🤖 Automation:
    • Justfile task runner for simple developer commands.
    • Code formatting and linting pre-configured with Black, Ruff, and Isort.
    • Optional pre-commit hooks to check code quality before git commits.

🏗️ Directory Layout

.
├── alembic/                  # Database migration versions and environments
├── src/
│   └── pygenesis/            # Python source package (auto-renamed by init.sh)
│       ├── api/              # API Routing & Dependency Injection
│       │   ├── deps.py       # Injectable database sessions & auth guards
│       │   └── v1/
│       │       ├── api.py    # Master version 1 endpoint router
│       │       └── endpoints/# API Endpoint Handlers (auth, users)
│       ├── core/             # Central configs, DB config, and security helpers
│       ├── models/           # SQLAlchemy Declarative Models (User)
│       ├── schemas/          # Pydantic validation schemas (User, Token)
│       └── main.py           # Application entrypoint, CORS setup, DB startup
├── tests/                    # Tests mirroring the source structure
│   ├── api/v1/endpoints/     # Endpoint tests (test_auth.py)
│   ├── conftest.py           # Pytest configurations and in-memory DB rollback fixtures
│   └── test_basic.py         # Basic load and import testing
├── Dockerfile                # Multi-stage production container build
├── docker-compose.yml        # FastAPI + PostgreSQL multi-container service layout
├── flake.nix                 # Nix development shell environment definition
├── Justfile                  # CLI task shortcuts
├── init.sh                   # Project renaming and initial configuration script
└── pyproject.toml            # Dependencies and linter rules configurations

🚀 Getting Started

Follow these steps to instantiate and run your new backend project:

1. Initialize Project Name

Clone the template, choose a project name, and run init.sh. The script supports dashes in project names; it will automatically convert directories and Python imports to snake_case but preserve the dash for package metadata and Docker.

# Clone the repository
git clone git@github.com:reze-dev/PyGenesis.git my-awesome-app
cd my-awesome-app

# Run the initialization script
./init.sh my-awesome-app

(The script will ask you if you want to reset Git history for a fresh start. Choose y to wipe the template's git commit logs or N to keep them).

2. Enter the Shell Environment

Activate the Nix development shell:

nix develop

Tip: If you use direnv, simply run direnv allow to automatically load and unload the environment whenever you navigate into or out of the project folder.

3. Launch Local Server

Run the application locally in development mode (with auto-reload):

just dev

By default, the server runs on http://localhost:8000. The interactive Swagger docs are available at http://localhost:8000/docs.


💡 Out-of-the-Box API Endpoints

The project comes preloaded with secure, standard identity endpoints:

Endpoint Method Security Description
/api/v1/users/register POST Public Register a new user account with email, password, and full_name.
/api/v1/auth/login/access-token POST Public OAuth2 password login. Returns a signed JWT access_token on success.
/api/v1/users/me GET Authenticated Retrieves profile information for the currently logged-in user.

Accessing Securing Endpoints Example

After registering a user and obtaining a token via /api/v1/auth/login/access-token, access protected resources by attaching the token to the header:

curl -X 'GET' \
  'http://localhost:8000/api/v1/users/me' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer YOUR_SIGNED_JWT_ACCESS_TOKEN'

💻 Daily Workflow Commands

All recurring commands are pre-configured in the Justfile. Use just to execute:

just dev                     # Start development server with reload
just test                    # Run pytest suite with in-memory DB transactions
just format                  # Auto-format and sort imports (Black, Ruff, Isort)
just lint                    # Check code compliance and formatting errors
just db-migrate "init db"    # Autogenerate an Alembic migration revision
just db-upgrade              # Apply pending Alembic migrations to database
just docker-up               # Start PostgreSQL and FastAPI containers in Docker
just docker-down             # Stop and remove Docker containers
just docker-logs             # Follow Docker container log output
just clean                   # Clean up test caches, pycache, and lockfiles

🔒 Configuration & Environment Variables

Settings are managed in src/pygenesis/core/config.py using pydantic-settings. Configure local defaults or Docker targets inside .env or system environment variables:

  • SECRET_KEY: Random cryptographic string used to sign JWT access tokens.
  • ACCESS_TOKEN_EXPIRE_MINUTES: Lifetime duration for tokens (default: 11520 minutes / 8 days).
  • SQLALCHEMY_DATABASE_URI: Connection URI. Defaults to sqlite:///./sql_app.db for local SQLite development, or PostgreSQL when running inside Docker.
  • API_V1_STR: API route version namespace (default: /api/v1).

About

A simple python skeleton which initializes your python project and manages your dependencies

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors