Skip to main content

A CLI tool to scaffold Python API projects following Clean Architecture principles with FastAPI

Project description

API Template PY

PyPI version Python 3.10+ License: MIT

A powerful CLI tool to scaffold Python API projects following Clean Architecture principles with FastAPI.

Features

  • Clean Architecture: Clear separation of concerns with layered architecture
  • FastAPI: Modern, fast, and production-ready web framework
  • Complete Project Structure: Pre-configured with all necessary layers
  • Interactive CLI: Beautiful terminal UI with prompts and colors
  • Dependency Injection: Built-in DI pattern for loose coupling
  • Type Hints: Full type safety throughout the codebase
  • Testing Ready: Pre-configured pytest setup with examples
  • Production Ready: CORS, logging, and error handling configured
  • Well Documented: Comprehensive docstrings and README

Architecture

Projects generated with api-template-py follow Clean Architecture:

┌────────────────────────────────────────────┐
│         API Layer (FastAPI)                │  ← Presentation Layer
│         api/v1/ - REST endpoints           │
└──────────────────┬─────────────────────────┘
                   ↓
┌────────────────────────────────────────────┐
│      Service Layer (Business Logic)        │  ← Business Layer
│      services/ - Domain logic              │
└──────────────────┬─────────────────────────┘
                   ↓
┌────────────────────────────────────────────┐
│    Repository Layer (Data Access)          │  ← Data Layer
│    repositories/ - Data persistence        │
└────────────────────────────────────────────┘

Installation

Install from PyPI:

pip install api-template-py

Or install from source:

git clone https://github.com/yourusername/api-template-py.git
cd api-template-py
pip install -e .

Quick Start

Create a New Project (Interactive)

api-template create

The CLI will prompt you for:

  • Project name
  • Description
  • Author name and email
  • Python version
  • Git initialization

Create a New Project (Non-Interactive)

api-template create my-api-project \
  --author "John Doe" \
  --email "john@example.com" \
  --python-version 3.10

Run Your New Project

cd my-api-project
python -m venv .venv
source .venv/bin/activate 
pip install -e .
uvicorn src.main:app --reload

Your API will be available at:

  • API: http://localhost:8000
  • Interactive Docs: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

Generated Project Structure

my-api-project/
├── src/                        # Source code
│   ├── api/                    # API Layer
│   │   ├── dependencies.py     # Dependency injection
│   │   └── v1/                 # API version 1
│   │       ├── health.py       # Health checks
│   │       └── items.py        # Example CRUD
│   ├── services/               # Service Layer
│   │   ├── base_service.py
│   │   └── item_service.py
│   ├── repositories/           # Repository Layer
│   │   ├── interfaces.py
│   │   ├── base_repository.py
│   │   └── item_repository.py
│   ├── models/                 # Domain Models
│   │   ├── domain.py
│   │   └── schemas.py
│   ├── core/                   # Core Infrastructure
│   │   ├── config.py
│   │   ├── constants.py
│   │   ├── exceptions.py
│   │   └── middleware.py
│   └── main.py                 # Entry point
├── tests/
│   └── test_items.py
├── pyproject.toml
├── README.md
├── .env.example
└── .gitignore

Key Design Patterns

1. Dependency Injection

# api/dependencies.py
@lru_cache
def get_item_service(
    repository: Annotated[ItemRepository, Depends(get_item_repository)]
) -> ItemService:
    return ItemService(repository=repository)

2. Repository Pattern

# repositories/interfaces.py
class IRepository(ABC, Generic[T]):
    @abstractmethod
    async def create(self, entity: T) -> T:
        pass

3. Service Layer Pattern

# services/item_service.py
class ItemService(BaseService[Item]):
    async def create_item(self, item_data: ItemCreate) -> ItemResponse:
        # Business logic here
        item = Item(**item_data.dict())
        return await self.repository.create(item)

4. DTO Pattern

# models/schemas.py
class ItemCreate(BaseModel):
    name: str
    price: float

class ItemResponse(BaseModel):
    id: int
    name: str
    price: float

Testing

Generated projects include test examples:

pytest
pytest --cov=src --cov-report=html

CLI Commands

api-template create

Create a new API project.

Options:

  • PROJECT_NAME - Project name (optional, will prompt if not provided)
  • --description, -d - Project description
  • --author, -a - Author name
  • --email, -e - Author email
  • --python-version, -p - Python version (3.10, 3.11, 3.12)
  • --no-git - Skip git initialization
  • --non-interactive - Non-interactive mode

Examples:

# Interactive mode
api-template create

# With project name
api-template create my-api

# Full non-interactive
api-template create my-api \
  --description "My API" \
  --author "Jane Doe" \
  --email "jane@example.com" \
  --python-version 3.11 \
  --non-interactive

What You Get

Pre-configured FastAPI Application

  • CORS middleware
  • Logging middleware
  • Custom exception handling
  • Lifespan events
  • OpenAPI documentation

Complete CRUD Example

  • Item model with validation
  • Service layer with business logic
  • Repository with in-memory storage
  • Full CRUD endpoints
  • Request/response schemas

Health Check Endpoints

  • /api/v1/health - Basic health check
  • /api/v1/health/ready - Readiness probe
  • /api/v1/health/live - Liveness probe

Development Tools

  • Type hints throughout
  • Comprehensive docstrings
  • pytest configuration
  • Environment variables support
  • Code formatting setup (Black, Ruff)

Documentation

For Generated Projects

Each generated project includes:

  • Comprehensive README with architecture explanation
  • Inline code documentation
  • Example implementations
  • Setup instructions
  • Development guidelines

Learn More

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

API Template PY Contributors

Acknowledgments

  • Inspired by Clean Architecture principles by Robert C. Martin
  • Built with FastAPI
  • CLI powered by Click and Rich

Support

If you have any questions or need help, please:

  • Open an issue on GitHub
  • Check existing issues for solutions
  • Read the generated project's README

Happy coding!

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

api_template_py-0.1.0.tar.gz (20.3 kB view details)

Uploaded Source

Built Distribution

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

api_template_py-0.1.0-py3-none-any.whl (25.6 kB view details)

Uploaded Python 3

File details

Details for the file api_template_py-0.1.0.tar.gz.

File metadata

  • Download URL: api_template_py-0.1.0.tar.gz
  • Upload date:
  • Size: 20.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for api_template_py-0.1.0.tar.gz
Algorithm Hash digest
SHA256 9a39fdc31ce180e57afd8f44ad4c4aae659dfef016d1fa3bde661697fd6efccb
MD5 819c90fcc038a171bca13636580fcee4
BLAKE2b-256 4db2dafbde3a490746b2090f78a455cf07d69e8b1b3aa6fbd0269f0ff0cbc6b7

See more details on using hashes here.

Provenance

The following attestation bundles were made for api_template_py-0.1.0.tar.gz:

Publisher: publish.yml on QuangDiy/api-template-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file api_template_py-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for api_template_py-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 48392e87808cd3618933c32d4a2e267b7bf8167ec775b195248a86cf08609919
MD5 72ed0952ed665a3016adb9f57356c4cb
BLAKE2b-256 afa208a93fa33e9cbf5471142eb57bf92e74deeebaa9cb1b072efbcbac435b89

See more details on using hashes here.

Provenance

The following attestation bundles were made for api_template_py-0.1.0-py3-none-any.whl:

Publisher: publish.yml on QuangDiy/api-template-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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