Skip to main content

Production-grade FastAPI microservice generator — like create-react-app, but for FastAPI.

Project description

 ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗      █████╗ ██████╗ ██╗
██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝     ██╔══██╗██╔══██╗██║
██║     ██████╔╝█████╗  ███████║   ██║   █████╗       ███████║██████╔╝██║
██║     ██╔══██╗██╔══╝  ██╔══██║   ██║   ██╔══╝       ██╔══██║██╔═══╝ ██║
╚██████╗██║  ██║███████╗██║  ██║   ██║   ███████╗     ██║  ██║██║     ██║
 ╚═════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝  ╚═╝   ╚══════╝     ╚═╝  ╚═╝╚═╝     ╚═╝

create-fastapi-service — Scaffold production-ready FastAPI microservices in seconds

PyPI Python FastAPI uv License: MIT PRs Welcome GitHub Stars GitHub Issues


Think create-react-app — but for Python microservices. One command generates a fully-wired, production-grade FastAPI service with PostgreSQL, Redis, Kafka, JWT, Docker, background workers, structured logging, OpenTelemetry tracing, and more.


Quick StartFeaturesCLI OptionsUse CasesGenerated StructureArchitecture


Why create-fastapi-service?

Setting up a new FastAPI microservice from scratch takes hours — configuring the database session, wiring routers, writing middleware, setting up auth, connecting Redis, adding Docker support… every time. create-fastapi-service eliminates all of that.

create-fastapi-service payment-service --postgres --redis --jwt --docker

↓ In under 2 minutes you get ↓

✓  uv init complete
✓  Directories and __init__.py files created
✓  PostgreSQL session (async SQLAlchemy)
✓  Redis client + @cache() decorator
✓  JWT RS256 handler
✓  Dockerfile + docker-compose.yml
✓  RSA key-pair generated in keys/
✓  Dependencies installed

  Swagger UI  →  http://localhost:8000/payment-service/docs
  Health      →  http://localhost:8000/payment-service/api/v1/health

✨ Features

Feature Description
🏗️ Project scaffold Full directory tree with __init__.py, config, models, schemas, services, repositories
🔌 Router wiring api_routerv1_router → endpoints, all pre-wired
🗄️ PostgreSQL Async SQLAlchemy 2.0 + asyncpg, session factory, auto table creation
🔴 Redis Async Redis client + @cache(ttl=60) decorator
🔐 JWT Auth (RS256) RSA key-pair auto-generated, create_access_token(), verify_token(), require_auth() FastAPI dependency
📨 Kafka aiokafka producer + consumer templates
⚙️ Background Workers asyncio-based worker loop with graceful start/stop
📦 Docker Multi-stage Dockerfile + docker-compose.yml with Postgres, Redis, Kafka services
🔄 Alembic Migration scaffold with async env
📝 Structured Logging timestamp | level | service | message format via get_logger()
🔍 Request Tracing X-Request-ID middleware on every request
🌐 OpenTelemetry Tracing helper with no-op fallback
🌍 Service-scoped URLs Every route, docs page and OpenAPI schema prefixed with /{service-name}
🛡️ Resilient Startup All infra connections wrapped — server starts even if Postgres/Redis/Kafka are offline
uv-powered Blazing-fast dependency install via uv
🧪 Test scaffold pytest + pytest-asyncio + httpx async test client pre-configured

🚀 Quick Start

Prerequisites

# Python 3.12+
python --version

# uv package manager
pip install uv
# or: curl -LsSf https://astral.sh/uv/install.sh | sh

Option 1 — Install once, use anywhere (recommended)

pip install create-fastapi-service

Then from any directory:

create-fastapi-service my-service --all
create-fastapi-service payment-api --postgres --redis --jwt
create-fastapi-service event-bus --kafka --workers

Option 2 — Clone & run

git clone https://github.com/me-lier/FastAPI-Fast.git
cd FastAPI-Fast
python create_fastapi_app.py my-service --all

Option 3 — Pin in requirements.txt

Add this line to any project's requirements.txt:

create-fastapi-service

Then:

pip install -r requirements.txt
create-fastapi-service my-service --all

After generating a service

cd my-service
uv run uvicorn app.main:app --reload

Open http://localhost:8000/my-service/docs 🎉


🎛️ CLI Options

create-fastapi-service <service-name> [options]
# or if running from clone:
python create_fastapi_app.py <service-name> [options]
Flag Description
--all Enable every feature at once
--postgres Async PostgreSQL via SQLAlchemy 2 + asyncpg
--redis Redis async client + @cache() decorator
--jwt JWT RS256 auth with auto-generated RSA key pair
--kafka Kafka producer + consumer (aiokafka)
--docker Dockerfile + docker-compose.yml
--workers Async background worker loop
--alembic Alembic migration scaffold
--interactive Prompt for each feature one-by-one

Examples

# Full stack
create-fastapi-service payment-service --all

# Auth + DB only
create-fastapi-service auth-service --postgres --jwt

# Event-driven service
create-fastapi-service event-service --kafka --workers --redis

# Choose features interactively
create-fastapi-service my-api --interactive

💡 Use Cases

1. Payment / Billing API

Needs a database, caching for speed, JWT auth to protect endpoints, and Docker for deployment.

create-fastapi-service payment-service --postgres --redis --jwt --docker

What you get:

  • Async PostgreSQL for storing transactions
  • Redis @cache() to avoid duplicate DB hits
  • JWT RS256 to protect /charge, /refund endpoints
  • docker-compose.yml with Postgres + Redis ready to go
cd payment-service
docker compose up --build
# Swagger UI → http://localhost:8000/payment-service/docs

2. Auth / Identity Service

Pure auth service — issues and validates JWT tokens, stores users in Postgres, runs DB migrations.

create-fastapi-service auth-service --postgres --jwt --alembic

What you get:

  • RSA key-pair auto-generated in keys/
  • create_access_token() + require_auth() ready to use
  • Alembic migrations pre-configured for user table
  • verify_token() endpoint for other services to validate tokens
cd auth-service
uv run alembic upgrade head
uv run uvicorn app.main:app --reload

3. Event-Driven Notification Service

Consumes Kafka events (e.g. order.placed) and processes them via background workers.

create-fastapi-service notification-service --kafka --workers --redis

What you get:

  • Kafka consumer template wired to asyncio event loop
  • Background worker loop with graceful shutdown
  • Redis to deduplicate or throttle notifications
cd notification-service
uv run uvicorn app.main:app --reload
# Worker starts automatically on app startup

4. Simple CRUD REST API

Just need a database and a clean project structure — no auth, no cache.

create-fastapi-service inventory-service --postgres

What you get:

  • Async SQLAlchemy session + models + repositories
  • Pre-wired GET/POST/PUT/DELETE /users endpoints to extend
  • Pydantic schemas, services layer, structured logging
cd inventory-service
uv run uvicorn app.main:app --reload
# http://localhost:8000/inventory-service/docs

5. Full Production Microservice

Everything — when you want the complete stack from day one.

create-fastapi-service orders-service --all

What you get: PostgreSQL + Redis + JWT + Kafka + Docker + Background Workers + Alembic migrations + test scaffold + OpenTelemetry tracing + structured logging + request ID middleware.

cd orders-service
docker compose up --build
# http://localhost:8000/orders-service/docs

6. Not sure what you need? Use interactive mode

create-fastapi-service my-service --interactive

Prompts you one feature at a time:

? Add PostgreSQL support? (y/n) y
? Add Redis caching? (y/n) n
? Add JWT authentication? (y/n) y
? Add Kafka messaging? (y/n) n
? Add Docker support? (y/n) y
? Add background workers? (y/n) n
? Add Alembic migrations? (y/n) y

📁 Generated Project Structure

my-service/
│
├── app/
│   ├── main.py                    # FastAPI app factory + lifespan
│   │
│   ├── api/
│   │   ├── router.py              # Root API router
│   │   └── v1/
│   │       ├── router.py          # v1 router
│   │       └── endpoints/
│   │           ├── health.py      # GET /health
│   │           └── users.py       # CRUD /users
│   │
│   ├── auth/
│   │   └── jwt_handler.py         # RS256 create/verify token
│   │
│   ├── cache/
│   │   ├── redis_client.py        # Async Redis connection
│   │   └── decorators.py          # @cache(ttl=60)
│   │
│   ├── kafka/
│   │   ├── producer.py            # publish(topic, payload)
│   │   └── consumer.py            # consume(handler)
│   │
│   ├── workers/
│   │   └── task_worker.py         # Async background loop
│   │
│   ├── logging/
│   │   └── logger.py              # get_logger(name)
│   │
│   ├── middleware/
│   │   ├── request_id.py          # X-Request-ID header
│   │   └── request_context.py     # Request/response logging
│   │
│   ├── models/
│   │   └── user_model.py          # SQLAlchemy ORM model
│   │
│   ├── repositories/
│   │   └── user_repository.py     # DB queries (CRUD)
│   │
│   ├── schemas/
│   │   └── user_schema.py         # Pydantic request/response
│   │
│   ├── services/
│   │   └── user_service.py        # Business logic
│   │
│   ├── db/
│   │   └── session.py             # Async SQLAlchemy engine + session
│   │
│   ├── dependencies/
│   │   └── auth.py                # Depends() factories
│   │
│   ├── utils/
│   │   └── tracing.py             # OpenTelemetry helpers
│   │
│   └── core/
│       └── config.py              # Pydantic Settings
│
├── keys/
│   ├── private.pem                # RSA private key (auto-generated)
│   └── public.pem                 # RSA public key  (auto-generated)
│
├── migrations/                    # Alembic scaffold
│   ├── env.py
│   └── versions/
│
├── tests/
│   └── test_health.py             # Async health check test
│
├── scripts/
│
├── Dockerfile                     # Multi-stage production image
├── docker-compose.yml             # API + Postgres + Redis + Kafka
├── gunicorn.conf.py               # UvicornWorker, cpu*2+1 workers
├── .env                           # Environment variables
├── pyproject.toml                 # Project metadata + pinned deps
└── README.md

🏛️ Architecture

Every generated service follows a strict layered architecture:

HTTP Request
     │
     ▼
┌─────────────────────────────────────────┐
│           Middleware Layer              │
│   RequestIDMiddleware (X-Request-ID)    │
│   RequestContextMiddleware (logging)    │
└─────────────────────────────────────────┘
     │
     ▼
┌─────────────────────────────────────────┐
│              Router Layer               │
│   /{service}/api/v1/users               │
│   /{service}/api/v1/health              │
└─────────────────────────────────────────┘
     │
     ▼
┌─────────────────────────────────────────┐
│             Endpoint Layer              │
│   HTTP validation, Depends injection    │
└─────────────────────────────────────────┘
     │
     ▼
┌─────────────────────────────────────────┐
│             Service Layer               │
│   Business logic, cache decorators      │
└─────────────────────────────────────────┘
     │
     ▼
┌─────────────────────────────────────────┐
│           Repository Layer              │
│   All DB queries, no business logic     │
└─────────────────────────────────────────┘
     │
     ▼
┌─────────────────────────────────────────┐
│           Database / Cache              │
│   PostgreSQL (asyncpg) │ Redis          │
└─────────────────────────────────────────┘

Each layer has one job:

Layer Responsibility
Endpoint Validate HTTP input/output, call service
Service Orchestrate business logic, apply caching
Repository All DB queries, zero business logic
Model Persistence schema (SQLAlchemy ORM)
Schema API contract (Pydantic)

🔒 JWT Authentication (RS256)

RSA keys are auto-generated at project creation time:

keys/private.pem   # signing key   (keep secret)
keys/public.pem    # verification key (share freely)

Create a token:

from app.auth.jwt_handler import create_access_token

token = create_access_token(subject="user@example.com")

Protect an endpoint:

from app.dependencies.auth import require_auth

@router.get("/secure")
async def secure_route(user: dict = Depends(require_auth)):
    return {"user": user}

Call the secured endpoint:

curl -H "Authorization: Bearer <token>" \
     http://localhost:8000/my-service/api/v1/users/secure

🔴 Redis Caching

from app.cache.decorators import cache

@cache(ttl=60)
async def get_user(user_id: int) -> dict:
    # result cached in Redis for 60 seconds
    return await repo.get_by_id(user_id)

Cache key is auto-derived from the function module, name, args and kwargs. No configuration needed.


📨 Kafka

Publish an event:

from app.kafka.producer import publish

await publish("user.created", {"id": 1, "email": "a@b.com"})

Consume events:

from app.kafka.consumer import consume

async def handle(msg: dict):
    print("received:", msg)

await consume(handler=handle)

🐳 Docker

# Start everything (API + Postgres + Redis + Kafka)
docker compose up --build

# API only
docker compose up api

Services:

Service Port
FastAPI 8000
PostgreSQL 5432
Redis 6379
Kafka 9092

🔄 Database Migrations (Alembic)

# After starting Postgres:
uv run alembic revision --autogenerate -m "init"
uv run alembic upgrade head

🌐 Service-Scoped URLs

Every URL is automatically prefixed with the service name so multiple services can run on the same host without path collisions:

http://localhost:8000/payment-service/docs
http://localhost:8000/payment-service/redoc
http://localhost:8000/payment-service/openapi.json
http://localhost:8000/payment-service/api/v1/health
http://localhost:8000/payment-service/api/v1/users

The prefix is derived from APP_NAME in .env at runtime — rename the service by changing one variable.


🧪 Running Tests

cd my-service
uv run pytest --cov=app tests/ -v

The test scaffold includes an async health check test using httpx.AsyncClient + ASGITransport (no server needed).


📦 Pinned Dependencies

All dependencies are installed with exact minimum versions:

Package Version Purpose
fastapi >=0.115.0 Web framework
uvicorn[standard] >=0.30.0 ASGI server
pydantic[email] >=2.7.0 Data validation + EmailStr
pydantic-settings >=2.3.0 Environment config
sqlalchemy[asyncio] >=2.0.30 Async ORM (includes greenlet)
asyncpg >=0.29.0 PostgreSQL async driver
redis >=5.0.4 Redis async client
aiokafka >=0.11.0 Kafka async client
python-jose[cryptography] >=3.3.0 JWT RS256
passlib[bcrypt] >=1.7.4 Password hashing
alembic >=1.13.0 DB migrations

🛡️ Resilient Startup

The generated service never crashes on startup due to missing infrastructure. Each connection attempt is wrapped:

INFO  | main | Starting payment-service (env=development)
WARN  | main | Database unavailable at startup: Connection refused
WARN  | main | Endpoints requiring DB will fail until PostgreSQL is reachable.
WARN  | main | Redis unavailable at startup: Connection refused
WARN  | main | Endpoints using @cache() will skip caching until Redis is reachable.
WARN  | main | Kafka unavailable at startup: ...
INFO  | main | Background worker started
INFO  | Uvicorn running on http://127.0.0.1:8000   ← always starts

⚙️ Production Server

# Gunicorn with UvicornWorker — auto-scales to cpu_count * 2 + 1 workers
uv run gunicorn -c gunicorn.conf.py app.main:app

🗺️ Roadmap

  • --graphql — Strawberry GraphQL integration
  • --grpc — gRPC service scaffold
  • --sentry — Sentry error tracking
  • --prometheus — Prometheus metrics endpoint
  • --celery — Celery task queue
  • pip install git+... — installable CLI via GitHub
  • pip install create-fastapi-service — published to PyPI

🤝 Contributing

Contributions are welcome! Here's how to get started:

  1. Fork the repo — github.com/me-lier/FastAPI-Fast
  2. Create a feature branch: git checkout -b feat/my-feature
  3. Make your changes to create_fastapi_app.py
  4. Test by generating a new project: python create_fastapi_app.py test-svc --all
  5. Push and open a Pull Request

Found a bug? Open an issue with steps to reproduce.


📄 License

MIT © 2025 Srinivas Deekonda — Free to use in personal and commercial projects.


👨‍💻 Author

Srinivas Deekonda

GitHub Email

Building tools that help developers ship production-grade services faster.


Built with ❤️ by Srinivas Deekonda — for developers who want to ship fast without cutting corners.

If this saved you time, give it a ⭐ on GitHub!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

create_fastapi_service-0.1.1.tar.gz (127.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

create_fastapi_service-0.1.1-py3-none-any.whl (35.9 kB view details)

Uploaded Python 3

File details

Details for the file create_fastapi_service-0.1.1.tar.gz.

File metadata

  • Download URL: create_fastapi_service-0.1.1.tar.gz
  • Upload date:
  • Size: 127.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for create_fastapi_service-0.1.1.tar.gz
Algorithm Hash digest
SHA256 240c29bed526d7d661fe74ed134ff6b7a1e2468348573b5f15f1608073689f20
MD5 f508ea70346b46d36c187cc36a594ece
BLAKE2b-256 d202f17745e762ab92c0d78c3d20035f738784b4fef83fcd92c88d492ca87c0e

See more details on using hashes here.

File details

Details for the file create_fastapi_service-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for create_fastapi_service-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ed9fbb96a5da769fa743bfb7e561dbc432a80b9d330d8dfe0c0d76bc484013ca
MD5 13f4bde89aa186956b6194de4582a898
BLAKE2b-256 5d7bf1c9889808381db40fdf5c0ecb7b3f22cb118cd4f997e8fec9be53413b1f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page