Claude Code Plugins

Community-maintained marketplace

Feedback

fastapi-backend-builder

@jennifer-mckinney/my-skills
1
0

Complete FastAPI backend development assistant. Scaffolds new projects, generates endpoints with tests, implements authentication, handles database operations, and provides best practices for building production-ready APIs. Specialized for async Python backends with proper structure, dependency injection, and testing.

Install Skill

1Download skill
2Enable skills in Claude

Open claude.ai/settings/capabilities and find the "Skills" section

3Upload to Claude

Click "Upload skill" and select the downloaded ZIP file

Note: Please verify skill by going through its instructions before using it.

SKILL.md

name fastapi-backend-builder
description Complete FastAPI backend development assistant. Scaffolds new projects, generates endpoints with tests, implements authentication, handles database operations, and provides best practices for building production-ready APIs. Specialized for async Python backends with proper structure, dependency injection, and testing.

FastAPI Backend Builder Skill

Expert assistance for building, structuring, and maintaining FastAPI applications with production-ready patterns and best practices.

When to Use This Skill

Use this skill when the user requests:

  • Creating a new FastAPI project from scratch
  • Adding new endpoints with proper structure
  • Implementing authentication and authorization
  • Setting up database connections and models
  • Creating WebSocket endpoints
  • Implementing background tasks
  • Adding middleware and dependencies
  • Structuring large FastAPI applications
  • Testing FastAPI endpoints
  • Deploying FastAPI applications
  • Debugging FastAPI issues

Quick Start Workflow

  1. Scaffold - Use scaffold_api.py to create project structure
  2. Add endpoints - Use add_endpoint.py to generate new routes with tests
  3. Configure - Set up environment variables and database
  4. Test - Run generated tests to verify behavior
  5. Deploy - Follow deployment guide in references

Scripts

scaffold_api.py

Creates a complete FastAPI project structure with all boilerplate code.

What it creates:

  • Project directory structure (app/, tests/, etc.)
  • Main FastAPI application with lifespan events
  • Example routers with CRUD operations
  • Database setup (SQLAlchemy or MongoDB)
  • Authentication scaffolding (JWT or OAuth2)
  • Environment configuration
  • Docker and docker-compose files
  • pytest configuration with fixtures
  • Requirements.txt with common dependencies
  • README with setup instructions

Command line usage:

# Create minimal API
python scripts/scaffold_api.py my-api

# Create API with database
python scripts/scaffold_api.py my-api --db postgres

# Create API with authentication
python scripts/scaffold_api.py my-api --auth jwt

# Full-featured API
python scripts/scaffold_api.py my-api --db postgres --auth jwt --docker

Options:

  • --db: Database type (postgres, mysql, sqlite, mongodb, none)
  • --auth: Auth type (jwt, oauth2, none)
  • --docker: Include Docker files
  • --websocket: Include WebSocket example
  • --celery: Include Celery for background tasks
  • --cors: Configure CORS middleware

Output structure:

my-api/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── config.py
│   ├── dependencies.py
│   ├── models/
│   │   ├── __init__.py
│   │   └── user.py
│   ├── schemas/
│   │   ├── __init__.py
│   │   └── user.py
│   ├── routers/
│   │   ├── __init__.py
│   │   ├── health.py
│   │   └── users.py
│   ├── services/
│   │   ├── __init__.py
│   │   └── user_service.py
│   └── database/
│       ├── __init__.py
│       └── session.py
├── tests/
│   ├── __init__.py
│   ├── conftest.py
│   └── test_users.py
├── .env.example
├── .gitignore
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
└── README.md

add_endpoint.py

Generates a new endpoint with all necessary files and tests.

What it creates:

  • Router file with CRUD operations
  • Pydantic schemas (Create, Update, Response)
  • SQLAlchemy model (if using database)
  • Service layer with business logic
  • Complete pytest test suite
  • Updates main.py to include router

Command line usage:

# Add simple endpoint
python scripts/add_endpoint.py posts

# Add endpoint with auth requirement
python scripts/add_endpoint.py posts --auth

# Add endpoint with custom operations
python scripts/add_endpoint.py posts --ops create,read,list

# Add WebSocket endpoint
python scripts/add_endpoint.py chat --websocket

Operations:

  • create - POST endpoint with validation
  • read - GET endpoint for single item
  • list - GET endpoint for multiple items with pagination
  • update - PUT endpoint with partial updates
  • delete - DELETE endpoint with soft delete option

Generated files:

app/routers/posts.py       # Router with endpoints
app/schemas/posts.py       # Pydantic models
app/models/posts.py        # Database model
app/services/post_service.py  # Business logic
tests/test_posts.py        # Complete test suite

validate_structure.py

Validates FastAPI project follows best practices.

What it checks:

  • Project structure follows conventions
  • All routers have corresponding tests
  • Environment variables properly configured
  • Dependencies properly injected
  • Pydantic models have proper validation
  • Database models have proper indexes
  • No business logic in routers
  • Proper error handling
  • Security best practices

Command line usage:

# Validate current project
python scripts/validate_structure.py

# Validate specific project
python scripts/validate_structure.py /path/to/project

# Check only specific aspects
python scripts/validate_structure.py --check structure,tests,security

Output:

 Project Structure: PASS
 Test Coverage: PASS (85%)
  Security: WARNING (Missing rate limiting)
 Error Handling: FAIL (Bare except in 3 files)

Recommendations:
1. Add rate limiting middleware
2. Replace bare except with specific exceptions
3. Add API documentation with examples

Reference Guides

Architecture Patterns (references/architecture.md)

Complete guide to structuring FastAPI applications. Read this when:

  • Starting a new project
  • Refactoring existing code
  • Scaling from small to large API
  • Implementing microservices
  • Understanding layered architecture

Key sections:

  • Project structure conventions
  • Layered architecture (Router → Service → Repository)
  • Dependency injection patterns
  • Configuration management
  • Error handling strategies
  • Logging and monitoring
  • Testing strategies
  • Deployment architectures

Best Practices (references/best_practices.md)

Expert guidance for production-ready FastAPI. Read this when:

  • Preparing for production deployment
  • Optimizing performance
  • Implementing security
  • Managing database connections
  • Handling file uploads
  • Implementing caching

Key sections:

  • Async best practices
  • Database session management
  • Authentication and authorization
  • Input validation and sanitization
  • Rate limiting and throttling
  • CORS configuration
  • File upload handling
  • Background task patterns
  • Caching strategies
  • Performance optimization

Database Integration (references/database.md)

Complete guide to database operations. Read this when:

  • Choosing a database
  • Setting up SQLAlchemy or MongoDB
  • Creating database models
  • Implementing migrations
  • Optimizing queries
  • Handling transactions

Key sections:

  • SQLAlchemy setup and patterns
  • MongoDB with Motor
  • Database migrations with Alembic
  • Connection pooling
  • Query optimization
  • Transaction management
  • Database testing strategies

Authentication Guide (references/authentication.md)

Implementing auth in FastAPI. Read this when:

  • Adding user authentication
  • Implementing JWT tokens
  • Setting up OAuth2
  • Managing sessions
  • Implementing role-based access

Key sections:

  • JWT token implementation
  • OAuth2 password flow
  • Refresh token patterns
  • Password hashing
  • Role-based access control (RBAC)
  • API key authentication
  • Session management

Common Workflows

Workflow 1: Create New API Project

# Step 1: Scaffold project
python scripts/scaffold_api.py my-api --db postgres --auth jwt --docker

# Step 2: Navigate to project
cd my-api

# Step 3: Set up environment
cp .env.example .env
# Edit .env with your settings

# Step 4: Start database
docker-compose up -d postgres

# Step 5: Run migrations
alembic upgrade head

# Step 6: Start development server
uvicorn app.main:app --reload

# Step 7: Run tests
pytest

# Step 8: Open API docs
open http://localhost:8000/docs

Workflow 2: Add New Endpoint

# Step 1: Generate endpoint
python scripts/add_endpoint.py products --auth

# Step 2: Customize business logic
# Edit app/services/product_service.py

# Step 3: Run tests
pytest tests/test_products.py -v

# Step 4: Test manually
open http://localhost:8000/docs#/products

Workflow 3: Implement Authentication

# Step 1: Add auth endpoint
python scripts/add_endpoint.py auth --no-crud

# Step 2: Customize auth logic
# Modify app/routers/auth.py
# Implement login, register, refresh token

# Step 3: Add auth dependency
# Edit app/dependencies.py

# Step 4: Protect existing endpoints
# Add depends=[Depends(get_current_user)] to routers

# Step 5: Test auth flow
pytest tests/test_auth.py -v

Workflow 4: Add WebSocket Support

# Step 1: Add WebSocket endpoint
python scripts/add_endpoint.py chat --websocket

# Step 2: Implement chat logic
# Edit app/routers/chat.py

# Step 3: Test WebSocket
# Use test client in tests/test_chat.py

# Step 4: Test in browser
open http://localhost:8000/chat

Decision Trees

Which Database Should I Use?

What type of data?
├─ Structured, relational → PostgreSQL or MySQL
│  └─ Need full-text search? → PostgreSQL
├─ Document-based, flexible schema → MongoDB
├─ Simple, embedded → SQLite
└─ Key-value, caching → Redis

Which Auth Method Should I Use?

Authentication needs?
├─ Simple API with users → JWT tokens
├─ Third-party login (Google, GitHub) → OAuth2
├─ Microservices → API keys or JWT
├─ Server-side sessions → Session cookies
└─ Machine-to-machine → Client credentials (OAuth2)

How Should I Structure My Project?

Project size?
├─ Small (< 5 endpoints) → Single router file
├─ Medium (5-20 endpoints) → Routers by resource
├─ Large (20+ endpoints) → Routers + services + domain modules
└─ Microservices → Separate FastAPI apps per domain

Best Practices Summary

Project Structure

  • Use layered architecture (router → service → repository)
  • Keep routers thin (just endpoint definitions)
  • Put business logic in services
  • Use dependency injection for database sessions
  • Separate Pydantic schemas from database models

Database

  • Use async database drivers (asyncpg, motor)
  • Always use connection pooling
  • Handle database sessions with dependencies
  • Use migrations for schema changes
  • Add indexes for frequently queried fields

Security

  • Never store passwords in plain text
  • Use proper CORS configuration
  • Validate all input with Pydantic
  • Implement rate limiting
  • Use HTTPS in production
  • Keep dependencies updated

Testing

  • Write tests for all endpoints
  • Use test database (separate from dev)
  • Mock external services
  • Test authentication flows
  • Aim for >80% coverage

Performance

  • Use async/await everywhere
  • Implement caching for expensive operations
  • Use connection pooling
  • Add pagination to list endpoints
  • Use background tasks for slow operations

Troubleshooting

Issue: "RuntimeError: Event loop is closed"

Solution: Using blocking code in async function. Use asyncio.run() or async library alternatives.


Issue: "422 Unprocessable Entity" on valid requests

Solution: Pydantic validation failing. Check schema matches request body. Use response_model_exclude_unset=True.


Issue: Database connection pool exhausted

Solution: Sessions not being closed. Use async with get_db() as db: or ensure dependencies properly manage lifecycle.


Issue: CORS errors in browser

Solution: Add CORS middleware with proper origins:

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Issue: Tests failing with "Database not found"

Solution: Tests using production database. Set up test database in conftest.py:

@pytest.fixture
def test_db():
    engine = create_async_engine("sqlite+aiosqlite:///:memory:")
    # ... setup test db

Example Queries This Skill Handles

  • "Create a new FastAPI project with PostgreSQL and JWT auth"
  • "Add a new endpoint for managing products"
  • "How do I implement WebSocket chat in FastAPI?"
  • "Set up database migrations with Alembic"
  • "Add authentication to my existing endpoints"
  • "How do I test FastAPI endpoints?"
  • "Implement background tasks with Celery"
  • "Add rate limiting to my API"
  • "Structure a large FastAPI application"
  • "Deploy FastAPI to production"

Integration with Development Workflow

This skill works best when integrated into your workflow:

  1. Project initialization: Use scaffold_api.py at project start
  2. Feature development: Use add_endpoint.py for new features
  3. Code review: Run validate_structure.py before commits
  4. CI/CD: Include validation in pipeline
  5. Documentation: Auto-generate OpenAPI docs from code

Metrics to Track

Monitor these for healthy FastAPI applications:

  • Response time - p50, p95, p99 latencies
  • Error rate - 4xx and 5xx responses
  • Throughput - Requests per second
  • Database query time - Identify slow queries
  • Test coverage - Maintain >80%
  • Dependency vulnerabilities - Keep updated

Quick Reference

Essential Commands

# Start dev server with auto-reload
uvicorn app.main:app --reload

# Start with custom host/port
uvicorn app.main:app --host 0.0.0.0 --port 8080

# Run tests with coverage
pytest --cov=app tests/

# Run specific test file
pytest tests/test_users.py -v

# Generate migration
alembic revision --autogenerate -m "Add users table"

# Apply migrations
alembic upgrade head

# Rollback migration
alembic downgrade -1

# Format code
black app/ tests/

# Lint code
ruff app/ tests/

Common Dependencies

fastapi>=0.104.0
uvicorn[standard]>=0.24.0
pydantic>=2.0.0
pydantic-settings>=2.0.0
sqlalchemy>=2.0.0
alembic>=1.12.0
asyncpg>=0.29.0          # PostgreSQL
aiomysql>=0.2.0          # MySQL
aiosqlite>=0.19.0        # SQLite
motor>=3.3.0             # MongoDB
python-jose[cryptography] # JWT
passlib[bcrypt]          # Password hashing
python-multipart         # File uploads
httpx                    # Testing & API calls
pytest>=7.4.0
pytest-asyncio>=0.21.0
pytest-cov>=4.1.0

Pro Tip: Always start with scaffold_api.py for consistency. Customize the generated code to match your specific needs, but keep the structure intact for maintainability.