fastapi-builder
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:
- Start with
assets/hello-world/main.py - Add endpoints with path parameters
- Add query parameters
- Use Pydantic models for request/response
Reference: None needed - hello-world template is self-contained
Phase 2: Professional Structure
Goal: Build scalable applications
Tasks:
- Use
scripts/init_project.pyto scaffold project - Understand layered architecture (see references/project-structure.md)
- Add configuration management
- Implement proper error handling
Reference: references/project-structure.md for architecture guidance
Phase 3: Database Integration
Goal: Persist data with SQLModel
Tasks:
- Define models with SQLModel
- Setup database connection and sessions
- Generate CRUD with
scripts/generate_crud.py - Create migrations with Alembic
Reference: references/database.md for SQLModel patterns, migrations, and queries
Phase 4: Authentication & Security
Goal: Secure APIs with JWT
Tasks:
- Implement password hashing
- Create login/register endpoints
- Add JWT token generation
- Protect endpoints with dependencies
Reference: references/authentication.md for JWT implementation and OAuth2 patterns
Phase 5: Testing
Goal: Write comprehensive tests
Tasks:
- Setup pytest with TestClient
- Write endpoint tests
- Test authentication flows
- Test with in-memory database
Reference: references/testing.md for test patterns and fixtures
Phase 6: Production Deployment
Goal: Deploy to production
Tasks:
- Containerize with Docker
- Setup environment variables
- Configure production server (Gunicorn)
- Add monitoring and logging
Reference: references/deployment.md for Docker, cloud platforms, and production configuration
Phase 7: Best Practices
Goal: Write maintainable code
Tasks:
- Apply separation of concerns
- Use dependency injection
- Implement proper error handling
- 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:
- project-structure.md - Professional project organization and layered architecture
- authentication.md - JWT auth, OAuth2, RBAC, API keys
- database.md - SQLModel, Alembic migrations, query patterns, async support
- testing.md - pytest, fixtures, endpoint tests, mocking
- deployment.md - Docker, production servers, cloud platforms, monitoring
- best-practices.md - Code quality, performance, security patterns
Scripts
Helper scripts to accelerate development:
scripts/init_project.py- Initialize new FastAPI project with professional structurescripts/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
- Start Simple: Begin with hello-world, understand the basics
- Use Scripts: Leverage init_project.py and generate_crud.py to save time
- Read References: Consult reference files when implementing specific features
- Follow Structure: Maintain layered architecture for scalability
- Test Early: Write tests as you build features
- Use Type Hints: FastAPI relies on type hints for validation and documentation
- Check Generated Docs: Always visit
/docsto see auto-generated API documentation
Troubleshooting
Import errors after generating CRUD:
- Update
app/api/v1/router.pyto include new endpoints - Import model in
alembic/env.pyfor 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: