Metadata-Version: 2.4
Name: create-fastapi-service
Version: 0.1.0
Summary: Production-grade FastAPI microservice generator — like create-react-app, but for FastAPI.
Project-URL: Homepage, https://github.com/me-lier/FastAPI-Fast
Project-URL: Repository, https://github.com/me-lier/FastAPI-Fast
Project-URL: Bug Tracker, https://github.com/me-lier/FastAPI-Fast/issues
Author-email: Srinivas Deekonda <srinivaslier@gmail.com>
License: MIT
License-File: LICENSE
Keywords: cli,fastapi,generator,microservice,scaffolding
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Code Generators
Requires-Python: >=3.11
Description-Content-Type: text/markdown

<div align="center">

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

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

[![Python](https://img.shields.io/badge/Python-3.12%2B-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.115%2B-009688?style=for-the-badge&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com)
[![uv](https://img.shields.io/badge/uv-package%20manager-DE5FE9?style=for-the-badge)](https://github.com/astral-sh/uv)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge)](LICENSE)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen?style=for-the-badge)](https://github.com/me-lier/FastAPI-Fast/pulls)
[![GitHub Stars](https://img.shields.io/github/stars/me-lier/FastAPI-Fast?style=for-the-badge&logo=github&color=gold)](https://github.com/me-lier/FastAPI-Fast/stargazers)
[![GitHub Issues](https://img.shields.io/github/issues/me-lier/FastAPI-Fast?style=for-the-badge&logo=github)](https://github.com/me-lier/FastAPI-Fast/issues)

<br/>

> **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.

<br/>

[Quick Start](#-quick-start) • [Features](#-features) • [CLI Options](#-cli-options) • [Generated Structure](#-generated-project-structure) • [Architecture](#-architecture) • [Examples](#-examples)

</div>

---

## 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.**

```
python create_fastapi_app.py 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_router` → `v1_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](https://github.com/astral-sh/uv) |
| 🧪 **Test scaffold** | pytest + pytest-asyncio + httpx async test client pre-configured |

---

## 🚀 Quick Start

### Prerequisites

```bash
# 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)

```bash
pip install git+https://github.com/me-lier/FastAPI-Fast.git
```

Then from **any directory**:

```bash
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

```bash
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 @ git+https://github.com/me-lier/FastAPI-Fast.git
```

Then:

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

---

### After generating a service

```bash
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

```bash
# 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
```

---

## 📁 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:

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

**Create a token:**
```python
from app.auth.jwt_handler import create_access_token

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

**Protect an endpoint:**
```python
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:**
```bash
curl -H "Authorization: Bearer <token>" \
     http://localhost:8000/my-service/api/v1/users/secure
```

---

## 🔴 Redis Caching

```python
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:**
```python
from app.kafka.producer import publish

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

**Consume events:**
```python
from app.kafka.consumer import consume

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

await consume(handler=handle)
```

---

## 🐳 Docker

```bash
# 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)

```bash
# 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

```bash
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

```bash
# 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
- [x] `pip install git+...` — installable CLI via GitHub
- [ ] `pip install create-fastapi-service` — publish to PyPI

---

## 🤝 Contributing

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

1. Fork the repo — [github.com/me-lier/FastAPI-Fast](https://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](https://github.com/me-lier/FastAPI-Fast/issues/new) with steps to reproduce.

---

## 📄 License

MIT © 2025 [Srinivas Deekonda](https://github.com/me-lier) — Free to use in personal and commercial projects.

---

## 👨‍💻 Author

<div align="center">

<img src="https://github.com/me-lier.png" width="80" style="border-radius: 50%"/>

**Srinivas Deekonda**

[![GitHub](https://img.shields.io/badge/GitHub-me--lier-181717?style=for-the-badge&logo=github)](https://github.com/me-lier)
[![Email](https://img.shields.io/badge/Email-srinivaslier%40gmail.com-D14836?style=for-the-badge&logo=gmail&logoColor=white)](mailto:srinivaslier@gmail.com)

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

</div>

---

<div align="center">

**Built with ❤️ by [Srinivas Deekonda](https://github.com/me-lier) — for developers who want to ship fast without cutting corners.**

If this saved you time, give it a ⭐ on [GitHub](https://github.com/me-lier/FastAPI-Fast)!

</div>
