fastapi-builder

SKILL.md

FastAPI Builder

Build production-ready FastAPI applications with professional structure, authentication, database integration, and deployment configurations.

Quick Start Workflow

1. Beginner: Hello World

For first-time FastAPI users, start with the minimal template:

# Copy hello-world template
cp -r assets/hello-world/* ./my-first-api/
cd my-first-api

# Install and run
pip install .
python main.py

Visit http://localhost:8000/docs to see interactive API documentation.

2. Intermediate: Professional Structure

For real projects, initialize with proper architecture:

python scripts/init_project.py my-api --with-auth --with-db
cd my-api
pip install -e .
python -m app.main

This creates:

  • Layered architecture (endpoints → services → repositories → database)
  • API versioning (/api/v1)
  • Configuration management
  • Docker support
  • Testing setup

3. Advanced: Add Features

Generate CRUD operations for models:

python scripts/generate_crud.py Task --fields title:str description:str is_completed:bool

This creates:

  • SQLModel model with timestamps
  • Service layer with business logic
  • API endpoints (Create, Read, Update, Delete, List)
  • Test templates

Development Path

Phase 1: Hello World → Basic API

Goal: Understand FastAPI fundamentals

Tasks:

  1. Start with assets/hello-world/main.py
  2. Add endpoints with path parameters
  3. Add query parameters
  4. Use Pydantic models for request/response

Reference: None needed - hello-world template is self-contained

Phase 2: Professional Structure

Goal: Build scalable applications

Tasks:

  1. Use scripts/init_project.py to scaffold project
  2. Understand layered architecture (see references/project-structure.md)
  3. Add configuration management
  4. Implement proper error handling

Reference: references/project-structure.md for architecture guidance

Phase 3: Database Integration

Goal: Persist data with SQLModel

Tasks:

  1. Define models with SQLModel
  2. Setup database connection and sessions
  3. Generate CRUD with scripts/generate_crud.py
  4. Create migrations with Alembic

Reference: references/database.md for SQLModel patterns, migrations, and queries

Phase 4: Authentication & Security

Goal: Secure APIs with JWT

Tasks:

  1. Implement password hashing
  2. Create login/register endpoints
  3. Add JWT token generation
  4. Protect endpoints with dependencies

Reference: references/authentication.md for JWT implementation and OAuth2 patterns

Phase 5: Testing

Goal: Write comprehensive tests

Tasks:

  1. Setup pytest with TestClient
  2. Write endpoint tests
  3. Test authentication flows
  4. Test with in-memory database

Reference: references/testing.md for test patterns and fixtures

Phase 6: Production Deployment

Goal: Deploy to production

Tasks:

  1. Containerize with Docker
  2. Setup environment variables
  3. Configure production server (Gunicorn)
  4. Add monitoring and logging

Reference: references/deployment.md for Docker, cloud platforms, and production configuration

Phase 7: Best Practices

Goal: Write maintainable code

Tasks:

  1. Apply separation of concerns
  2. Use dependency injection
  3. Implement proper error handling
  4. Add caching and background tasks

Reference: references/best-practices.md for patterns and anti-patterns

Common Tasks

Starting a New Project

# Minimal project
python scripts/init_project.py my-api

# With authentication and database
python scripts/init_project.py my-api --with-auth --with-db

Adding CRUD for a Resource

# Generate model, service, endpoints, and tests
python scripts/generate_crud.py Product --fields name:str price:float stock:int

# Update router to include new endpoints
# See app/api/v1/router.py

Adding Authentication

If not included during initialization, see references/authentication.md for:

  • JWT token implementation (core/security.py)
  • Login/register endpoints (api/v1/endpoints/auth.py)
  • Protected route dependencies (dependencies.py)

Setting Up Database

See references/database.md for:

  • SQLModel configuration
  • Alembic migrations setup
  • Connection pooling
  • Async database support

Writing Tests

See references/testing.md for:

  • Test fixtures (sessions, clients, auth)
  • Endpoint testing patterns
  • Service layer testing
  • Mocking external services

Deployment

See references/deployment.md for:

  • Docker and docker-compose
  • Production server configuration
  • Cloud platform deployment (Railway, Render, Fly.io)
  • Nginx reverse proxy
  • Environment management

Project Structure

Professional FastAPI projects follow this structure:

project/
├── app/
│   ├── api/v1/           # API endpoints
│   │   ├── router.py     # Route aggregation
│   │   └── endpoints/    # Individual endpoint files
│   ├── core/             # Core utilities (security, database)
│   ├── models/           # SQLModel database models
│   ├── schemas/          # Pydantic request/response schemas
│   ├── services/         # Business logic layer
│   ├── repositories/     # Database access layer (optional)
│   ├── config.py         # Configuration
│   └── main.py           # Application entry point
├── tests/                # Test files
├── alembic/              # Database migrations
├── pyproject.toml        # Dependencies
├── .env                  # Environment variables
└── Dockerfile            # Container configuration

References

Detailed documentation organized by topic:

Scripts

Helper scripts to accelerate development:

  • scripts/init_project.py - Initialize new FastAPI project with professional structure
  • scripts/generate_crud.py - Generate CRUD operations (model, service, endpoints, tests)

Assets

Ready-to-use templates:

  • assets/hello-world/ - Minimal FastAPI application for learning

Example Workflow

Building a Todo API

# 1. Initialize project
python scripts/init_project.py todo-api --with-auth --with-db
cd todo-api

# 2. Generate CRUD for Task model
python scripts/generate_crud.py Task \
    --fields title:str description:Optional[str] is_completed:bool

# 3. Update router to include task endpoints
# Edit app/api/v1/router.py:
#   from app.api.v1.endpoints import tasks
#   api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])

# 4. Create database migration
alembic revision --autogenerate -m "Add tasks table"
alembic upgrade head

# 5. Run and test
python -m app.main
# Visit http://localhost:8000/docs

# 6. Write tests
# See tests/test_api/test_tasks.py

# 7. Deploy
docker build -t todo-api .
docker run -p 8000:8000 todo-api

Adding Authentication to Existing Project

# 1. Read authentication reference
# See references/authentication.md

# 2. Create core/security.py with JWT utilities
# Copy implementation from authentication.md

# 3. Create auth endpoints
# Create app/api/v1/endpoints/auth.py
# Add login and register endpoints

# 4. Create dependencies.py with get_current_user
# Implement user authentication dependency

# 5. Protect endpoints
# Add Depends(get_current_user) to protected routes

# 6. Test authentication flow
# See references/testing.md for auth testing patterns

Tips for Success

  1. Start Simple: Begin with hello-world, understand the basics
  2. Use Scripts: Leverage init_project.py and generate_crud.py to save time
  3. Read References: Consult reference files when implementing specific features
  4. Follow Structure: Maintain layered architecture for scalability
  5. Test Early: Write tests as you build features
  6. Use Type Hints: FastAPI relies on type hints for validation and documentation
  7. Check Generated Docs: Always visit /docs to see auto-generated API documentation

Troubleshooting

Import errors after generating CRUD:

  • Update app/api/v1/router.py to include new endpoints
  • Import model in alembic/env.py for migrations

Database connection errors:

  • Check DATABASE_URL in .env
  • Ensure database is running (for PostgreSQL/MySQL)
  • Run migrations: alembic upgrade head

Authentication not working:

  • Verify SECRET_KEY is set in .env
  • Check token format in requests: Authorization: Bearer <token>
  • Ensure password hashing dependencies are installed

Tests failing:

  • Check conftest.py has proper fixtures
  • Verify test database configuration
  • Use in-memory SQLite for tests: sqlite:///:memory:
Weekly Installs
2
First Seen
Feb 26, 2026
Installed on
opencode2
claude-code2
github-copilot2
codex2
kimi-cli2
gemini-cli2