Skip to content

Latest commit

 

History

History
664 lines (507 loc) · 17.2 KB

File metadata and controls

664 lines (507 loc) · 17.2 KB

FastAPI Scaffold - Fully Automated Project Generator

A powerful CLI tool that creates production-ready FastAPI projects with complete automation - from scaffolding to running server in one command!

✨ What Makes This Special?

🚀 100% Automated Setup - Just answer a few questions, everything else is automatic
📦 Auto Virtual Environment - Creates and configures venv automatically
🎯 Auto Poetry Install - Installs Poetry in your project's venv
🔄 Auto Dependencies - Installs latest compatible versions automatically
💾 Auto Database Setup - Initializes database with Alembic migrations
🔐 JWT Authentication - Optional complete auth system (login, register, protected routes)
📝 Interactive Prompts - No need to remember command flags
🎨 Beautiful CLI - Rich colored output with progress indicators
Latest Versions - Always installs latest compatible package versions

🎬 Quick Demo

fastapi-create-project

That's it! Just run this one command and answer the prompts:

  • Project name (default: fastapi-project)
  • Developer name (optional)
  • Developer email (optional)
  • Database type (default: SQLite)
  • Include Docker? (default: No)
  • Include tests? (default: No)
  • Include JWT auth? (default: No)

The CLI will automatically:

  1. ✅ Generate complete project structure
  2. ✅ Create virtual environment (python -m venv venv)
  3. ✅ Install Poetry in the venv
  4. ✅ Create .env file from template
  5. ✅ Install all dependencies with poetry install
  6. ✅ Initialize database with alembic upgrade head
  7. ✅ You're ready to code! Just cd project-name && source venv/bin/activate

📦 Installation

Recommended: Global Installation with pip

cd /Users/pinkleshparjapati/Desktop/fastapi-create-project
pip install .

# Verify
fastapi-create-project --help

Alternative: Global Installation with pipx

# Install pipx (if you don't have it)
python -m pip install --user pipx
python -m pipx ensurepath

# Install the CLI tool globally
cd /Users/pinkleshparjapati/Desktop/fastapi-create-project
pipx install .

# Done! Use from anywhere
fastapi-create-project --help

For Developers Only: Editable Installation

Only use this if you're modifying the CLI tool code:

cd /Users/pinkleshparjapati/Desktop/fastapi-create-project
source venv/bin/activate
pip install -e .  # -e = editable mode, changes reflect immediately

Uninstallation

If you installed with pipx:

pipx uninstall fastapi-create-project

If you installed with pip:

pip uninstall fastapi-create-project

Note: You don't need to install Poetry globally! The CLI installs it automatically in each project.

🚀 Usage (Creating Projects)

Super Simple - Just One Command:

fastapi-create-project

That's it! Press Enter for all prompts to get a working FastAPI project in seconds!

What Happens Automatically:

  1. ✅ Asks for project details (name, developer info)
  2. ✅ Generates complete project structure
  3. ✅ Creates virtual environment
  4. ✅ Installs Poetry
  5. ✅ Runs poetry add for all dependencies (gets latest versions)
  6. ✅ Runs poetry install and poetry update
  7. ✅ Creates .env with unique JWT_SECRET_KEY
  8. ✅ Initializes database with Alembic
  9. ✅ Ready to run!

After Creation:

cd your-project-name
source venv/bin/activate
poetry run uvicorn app.main:app --reload

Open: http://localhost:8000/docs


🎯 Detailed Usage

Option 1: Fully Interactive (Recommended)

fastapi-create-project

The CLI will ask you:

  1. Project name - Enter your project name (default: fastapi-project)
  2. Developer name - Your name (appears in pyproject.toml)
  3. Developer email - Your email (appears in pyproject.toml)
  4. Database - Choose PostgreSQL, MySQL, or SQLite (default: SQLite - can change in .env)
  5. Docker - Include Docker configuration? (default: No)
  6. Tests - Include pytest setup? (default: No)
  7. JWT Auth - Include JWT authentication? (default: No)

Then sit back! The CLI will:

  • Generate all files with your configuration
  • Create virtual environment (python -m venv venv)
  • Install Poetry in the venv
  • Run poetry add fastapi[standard] sqlalchemy alembic... (latest versions)
  • Run poetry install and poetry update
  • Create .env file with auto-generated JWT_SECRET_KEY
  • Initialize database with alembic upgrade head

When it's done, just:

cd your-project-name
source venv/bin/activate
poetry run uvicorn app.main:app --reload

Visit: http://localhost:8000/docs

Option 2: Provide Project Name

fastapi-create-project my-awesome-api

CLI will ask for developer info, database, Docker, tests, and JWT.

Option 3: Non-Interactive (For Scripts/CI)

fastapi-create-project my-api \
  --name "John Doe" \
  --email "john@example.com" \
  -d sqlite \
  --no-docker \
  --no-tests \
  --no-jwt

Option 4: Skip Automation (Manual Setup)

fastapi-create-project my-api --no-auto-setup

This only generates files without creating venv or installing dependencies.

📋 Command Options

Option Short Description
project_name - Project name (optional, will prompt if not provided)
--name - Developer name for pyproject.toml
--email - Developer email for pyproject.toml
--database -d Database: postgresql, mysql, or sqlite (default: sqlite)
--docker / --no-docker - Include Docker configuration (default: No)
--tests / --no-tests - Include pytest setup (default: No)
--jwt / --no-jwt - Include JWT authentication (default: No)
--path - Where to create project (default: current directory)
--no-auto-setup - Skip venv/poetry/installation automation

🎯 Example Workflows

Quick Start (Just Press Enter for Defaults!)

fastapi-create-project
# Just press Enter for all prompts to use defaults:
# - Project name: fastapi-project
# - SQLite database (no setup needed!)
# - No Docker
# - No Tests  
# - No JWT
# Done! Start coding immediately

Production Setup (PostgreSQL)

fastapi-create-project
# Choose PostgreSQL, Yes Docker, Yes Tests, Yes JWT
# Edit .env with your PostgreSQL credentials
# docker-compose up -d

Automated CI/CD Script

fastapi-create-project ci-api \
  -d sqlite \
  --no-docker \
  --tests \
  --no-jwt \
  --name "CI Bot" \
  --email "ci@company.com"

📁 Generated Project Structure

my-project/
├── app/
│   ├── main.py                 # FastAPI application
│   ├── api/v1/
│   │   ├── api.py             # API router
│   │   └── endpoints/
│   │       ├── users.py       # CRUD example
│   │       └── health.py      # Health checks
│   ├── core/
│   │   └── config.py          # Settings (Pydantic)
│   ├── crud/
│   │   └── user.py            # Database operations
│   ├── db/
│   │   ├── base.py            # Model registry
│   │   └── database.py        # DB connection
│   ├── models/
│   │   └── user.py            # SQLAlchemy models
│   ├── schemas/
│   │   └── user.py            # Pydantic schemas
│   └── services/              # Business logic
├── alembic/
│   ├── versions/              # Migrations
│   └── env.py                 # Alembic config
├── tests/                     # Pytest tests (optional)
├── venv/                      # Virtual environment (auto-created)
├── .env                       # Environment vars (auto-created)
├── .env.example              # Template
├── .gitignore                # Git ignore
├── pyproject.toml            # Poetry config
├── alembic.ini               # Alembic config
├── Dockerfile                # Docker (optional)
├── docker-compose.yml        # Docker Compose (optional)
├── pytest.ini                # Pytest config (optional)
└── README.md                 # Documentation

🎨 What Gets Automatically Installed

All with latest compatible versions (no hard-coded version numbers):

Core Framework:

  • FastAPI ^0.115 (any 0.115.x)
  • Uvicorn ^0.32 with standard extras
  • SQLAlchemy ^2.0 (any 2.x)
  • Alembic ^1.14 (any 1.x)
  • Pydantic ^2.10 + pydantic-settings ^2.6

Database Drivers:

  • PostgreSQL: psycopg2-binary ^2.9
  • MySQL: pymysql ^1.1
  • SQLite: Built-in

Security:

  • python-jose ^3.3 (JWT)
  • passlib ^1.7 (password hashing)
  • python-multipart ^0.0.17

Development:

  • python-dotenv ^1.0

Testing (if selected):

  • pytest ^8.0
  • pytest-cov ^6.0
  • httpx ^0.27

The ^ constraint means Poetry will install the latest compatible version within that major.minor range!

🔥 Features Included

🎯 Complete CRUD Example

Working user management system with:

  • Create user with password hashing
  • Read users (list and detail)
  • Update user
  • Delete user
  • Email and username uniqueness
  • Timestamps (created_at, updated_at)

🏥 Health Checks

  • GET /api/v1/health - Application status
  • GET /api/v1/health/db - Database connectivity

📚 Auto-Generated Documentation

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • OpenAPI JSON: http://localhost:8000/api/v1/openapi.json

🔐 JWT Authentication (Optional)

When JWT is enabled, you get:

  • Login endpoint (POST /api/v1/auth/login)
  • Register endpoint (POST /api/v1/auth/register)
  • Get current user (GET /api/v1/auth/me)
  • Password hashing with bcrypt
  • JWT token generation and verification
  • Protected routes example with get_current_user dependency
  • OAuth2 compatible (works with FastAPI's built-in docs)

Security Features:

  • Password hashing with bcrypt
  • JWT token structure (python-jose)
  • Token expiration handling
  • CORS middleware configured
  • Environment-based secrets

🗄️ Database Features

  • Alembic migrations pre-configured
  • Auto-generated initial migration
  • Database connection pooling
  • SQLAlchemy 2.0 syntax
  • Support for PostgreSQL, MySQL, SQLite

🐳 Docker Support (Optional)

  • Dockerfile with Poetry
  • docker-compose.yml with database service
  • Production-ready container setup

✅ Testing Setup (Optional)

  • Pytest configured
  • Test database setup
  • Example tests included
  • Coverage reporting ready

🎓 After Project Creation

Start Development Server

cd your-project
source venv/bin/activate
poetry run uvicorn app.main:app --reload

Run Tests

poetry run pytest
poetry run pytest --cov=app

Create New Migration

poetry run alembic revision --autogenerate -m "Add new table"
poetry run alembic upgrade head

Add New Dependency

poetry add redis
poetry add --group dev black

Using Docker

docker-compose up -d          # Start services
docker-compose logs -f app    # View logs
docker-compose down           # Stop services

🎯 Development Workflow

1. Create Project

fastapi-create-project blog-api

2. Add Your Models

Edit app/models/post.py:

from sqlalchemy import Column, Integer, String, Text
from app.db.database import Base

class Post(Base):
    __tablename__ = "posts"
    id = Column(Integer, primary_key=True)
    title = Column(String, nullable=False)
    content = Column(Text)

3. Import in Registry

Edit app/db/base.py:

from app.models.user import User  # noqa
from app.models.post import Post  # noqa - Add this

4. Create Schemas

Edit app/schemas/post.py (Pydantic models for API)

5. Add CRUD Operations

Edit app/crud/post.py (database operations)

6. Create Endpoints

Edit app/api/v1/endpoints/posts.py (API routes)

7. Register Router

Edit app/api/v1/api.py:

from app.api.v1.endpoints import posts
api_router.include_router(posts.router, prefix="/posts", tags=["posts"])

8. Generate Migration

poetry run alembic revision --autogenerate -m "Add posts"
poetry run alembic upgrade head

9. Test & Iterate

poetry run pytest
poetry run uvicorn app.main:app --reload

💡 Tips & Best Practices

  1. Let Poetry Manage Versions - Don't pin exact versions, use ^ constraints
  2. Use .env for Secrets - Never commit .env to git
  3. Generate Secure Keys - openssl rand -hex 32 for SECRET_KEY
  4. Write Tests - Use the included test structure
  5. Migration Strategy - Create migration for every model change
  6. Type Hints - FastAPI works best with full type annotations
  7. API Versioning - Keep using /api/v1/ prefix for backwards compatibility
  8. Documentation - Add docstrings to your endpoints
  9. Virtual Environment - Always activate venv before working
  10. Docker for Production - Use docker-compose for deployment

🐛 Troubleshooting

Project Creation Fails

# Check Python version (need 3.8+)
python --version

# Reinstall CLI tool
cd /Users/pinkleshparjapati/Desktop/fastapi-create-project
source venv/bin/activate
pip install --upgrade pip
pip install -e .

Poetry Install Fails in Generated Project

cd your-project
source venv/bin/activate
pip install --upgrade pip poetry
poetry install -vvv  # Verbose mode

Database Connection Error

Check your .env file:

# For SQLite
DATABASE_URL=sqlite:///./app.db

# For PostgreSQL  
DATABASE_URL=postgresql://user:password@localhost:5432/dbname

# For MySQL
DATABASE_URL=mysql://user:password@localhost:3306/dbname

Migration Issues

# Reset database (development only!)
poetry run alembic downgrade base
poetry run alembic upgrade head

# Or create fresh migration
poetry run alembic revision --autogenerate -m "Initial"
poetry run alembic upgrade head

Port 8000 Already in Use

# Use different port
poetry run uvicorn app.main:app --reload --port 8001

# Or kill existing process
lsof -ti:8000 | xargs kill -9  # macOS/Linux
netstat -ano | findstr :8000   # Windows

Import Errors

# Reinstall dependencies
poetry install

# Verify installation
poetry show

# Check Python path
poetry run python -c "import fastapi; print(fastapi.__version__)"

🎁 What You Get

✅ Production-ready project structure
✅ Virtual environment automatically created
✅ Poetry installed and configured (latest versions)
✅ All dependencies installed via poetry add (no hardcoded versions)
✅ Database initialized with Alembic
.env file created with auto-generated JWT_SECRET_KEY
✅ Working CRUD example
✅ API documentation (Swagger + ReDoc)
✅ JWT authentication (optional: register, login, protected routes)
✅ Argon2 password hashing (more secure than bcrypt)
✅ SQLAlchemy 2.0 compatible code
✅ Alembic migrations reading from .env
✅ Testing framework with pytest (optional)
✅ Docker setup with docker-compose (optional)
✅ Beautiful README in your project

📚 Learn More

🤝 Contributing

Want to improve this tool?

  1. Edit fastapi_scaffold/cli.py - Command-line interface
  2. Edit fastapi_scaffold/generator.py - Project generation logic
  3. Edit fastapi_scaffold/templates.py - File templates
  4. Run pip install -e . to test changes
  5. Create a test project to verify

📝 Version & License

Version: 0.1.0
Created: October 7, 2025
Python: 3.8+
License: MIT


📖 Quick Reference

Installation:

# Global installation (use from anywhere)
cd /Users/pinkleshparjapati/Desktop/fastapi-create-project
pipx install .
# or: pip install .

Check Version:

fastapi-create-project --version
# or: fastapi-create-project -V

Create Project:

fastapi-create-project
# Just press Enter for defaults!

Run Project:

cd your-project
source venv/bin/activate
poetry run uvicorn app.main:app --reload

Key Features:

  • ✅ Auto SQLite (change to PostgreSQL/MySQL in .env)
  • ✅ Auto-generated unique JWT_SECRET_KEY
  • ✅ Latest package versions via poetry add
  • ✅ Argon2 password hashing
  • ✅ SQLAlchemy 2.0 compatible
  • ✅ All settings from .env file
  • ✅ No hardcoded values

Generated Endpoints:

  • GET /api/v1/health - Health check
  • GET /api/v1/health/db - Database check
  • POST /api/v1/auth/register - Register (if JWT enabled)
  • POST /api/v1/auth/login - Login (if JWT enabled)
  • GET /api/v1/auth/me - Current user (if JWT enabled)
  • GET /api/v1/users - List users
  • GET /api/v1/users/{id} - Get user
  • PUT /api/v1/users/{id} - Update user
  • DELETE /api/v1/users/{id} - Delete user

🌟 Star This Project

If this tool saved you time, give it a star! ⭐

Made with ❤️ for FastAPI developers who want to start coding faster!

Questions? Issues? Check the generated project's README for more details.

Happy Coding! 🚀