Skip to main content

Template Info

Category Api
Difficulty
Intermediate
Setup Time 15 minutes
License MIT
Last Updated 2024-01-15
Download Raw Files View on GitHub Live Demo

Key Features

  • FastAPI with automatic OpenAPI documentation
  • SQLAlchemy ORM with Alembic migrations
  • JWT authentication and authorization
  • Pydantic models for request/response validation
  • Docker containerization
  • Comprehensive test suite with pytest
  • Pre-configured logging and error handling
  • Environment-based configuration

Use Cases

  • REST API backends for web applications
  • Microservices architecture
  • API-first development
  • Rapid prototyping
  • Production-ready web services
Templates Api FastAPI Starter Template

FastAPI Starter Template

Featured Free License

A complete FastAPI starter template with authentication, database integration, and best practices

Setup Time
15 minutes
Difficulty
Intermediate
Components
4 included

Overview

This FastAPI starter template provides a solid foundation for building production-ready APIs. It includes authentication, database integration, comprehensive testing, and deployment configurations.

The template follows FastAPI best practices and includes everything you need to get started quickly while maintaining code quality and scalability.

Features

Core FastAPI Setup

  • High Performance: Built on Starlette and Pydantic for maximum speed
  • Automatic Documentation: Interactive API docs with Swagger UI and ReDoc
  • Type Safety: Full Python type hints throughout the codebase
  • Async Support: Native async/await support for high concurrency

Database Integration

  • SQLAlchemy ORM: Powerful and flexible database toolkit
  • Alembic Migrations: Database schema version control
  • Connection Pooling: Optimized database connections
  • Multiple Database Support: PostgreSQL, MySQL, SQLite

Authentication & Security

  • JWT Authentication: Secure token-based authentication
  • Password Hashing: Bcrypt for secure password storage
  • CORS Configuration: Cross-origin resource sharing setup
  • Security Headers: Built-in security middleware

Development Experience

  • Hot Reload: Automatic server restart during development
  • Comprehensive Testing: pytest with async test support
  • Code Quality: Pre-configured linting and formatting
  • Environment Management: Environment-based configuration

Quick Start

Prerequisites

Make sure you have the following installed:

  • Python 3.8 or higher
  • pip (Python package manager)
  • Git
  • PostgreSQL (optional, SQLite works for development)

Installation

  1. Clone or download the template

    1
    2
    
    git clone https://github.com/pragmatic-ai-stack/fastapi-starter.git
    cd fastapi-starter
    
  2. Create virtual environment

    1
    2
    
    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. Install dependencies

    1
    
    pip install -r requirements.txt
    
  4. Set up environment variables

    1
    2
    
    cp .env.example .env
    # Edit .env with your configuration
    
  5. Initialize database

    1
    
    alembic upgrade head
    
  6. Run the application

    1
    
    uvicorn app.main:app --reload
    

Expected Output

1
2
3
4
5
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28720]
INFO:     Started server process [28722]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

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

Project Structure

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
fastapi-starter/
├── app/
│   ├── __init__.py
│   ├── main.py              # FastAPI application
│   ├── api/
│   │   ├── __init__.py
│   │   ├── deps.py          # Dependencies
│   │   └── v1/
│   │       ├── __init__.py
│   │       ├── api.py       # API router
│   │       ├── auth.py      # Authentication routes
│   │       └── users.py     # User routes
│   ├── core/
│   │   ├── __init__.py
│   │   ├── config.py        # Configuration
│   │   └── security.py     # Security utilities
│   ├── crud/
│   │   ├── __init__.py
│   │   └── user.py         # User CRUD operations
│   ├── models/
│   │   ├── __init__.py
│   │   └── user.py         # SQLAlchemy models
│   └── schemas/
│       ├── __init__.py
│       └── user.py         # Pydantic schemas
├── tests/
│   ├── __init__.py
│   ├── conftest.py         # Test configuration
│   └── test_api.py         # API tests
├── alembic/                # Database migrations
├── docker-compose.yml      # Docker services
├── Dockerfile             # Docker image
├── requirements.txt       # Python dependencies
├── .env.example          # Environment template
└── README.md             # Documentation

Configuration

The template uses environment variables for configuration. Copy .env.example to .env and customize:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Database
DATABASE_URL=postgresql://user:password@localhost/dbname

# Security
SECRET_KEY=your-secret-key-here
ACCESS_TOKEN_EXPIRE_MINUTES=30

# CORS
BACKEND_CORS_ORIGINS=["http://localhost:3000"]

# Environment
ENVIRONMENT=development
DEBUG=True

API Endpoints

Authentication

  • POST /api/v1/auth/login - User login
  • POST /api/v1/auth/register - User registration
  • POST /api/v1/auth/refresh - Refresh access token

Users

  • GET /api/v1/users/me - Get current user
  • PUT /api/v1/users/me - Update current user
  • GET /api/v1/users/ - List users (admin only)

Health Check

  • GET /health - Application health status

Testing

Run the test suite:

1
2
3
4
5
6
7
8
# Run all tests
pytest

# Run with coverage
pytest --cov=app

# Run specific test file
pytest tests/test_api.py

Deployment

Docker Deployment

  1. Build the image

    1
    
    docker build -t fastapi-starter .
    
  2. Run with docker-compose

    1
    
    docker-compose up -d
    

Production Deployment

For production deployment, consider:

  • Using a production WSGI server (Gunicorn with Uvicorn workers)
  • Setting up a reverse proxy (nginx)
  • Configuring SSL certificates
  • Setting up monitoring and logging
  • Using a managed database service

Customization Guide

Adding New Endpoints

  1. Create a new router in app/api/v1/
  2. Define Pydantic schemas in app/schemas/
  3. Add database models in app/models/
  4. Implement CRUD operations in app/crud/
  5. Include router in app/api/v1/api.py

Database Models

Add new SQLAlchemy models in app/models/:

1
2
3
4
5
6
7
8
from sqlalchemy import Column, Integer, String, DateTime
from app.db.base_class import Base

class Item(Base):
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String)
    created_at = Column(DateTime, default=datetime.utcnow)

Background Tasks

For background tasks, integrate Celery:

1
2
3
4
5
6
7
8
from celery import Celery

celery_app = Celery("fastapi-starter")

@celery_app.task
def send_email(email: str, message: str):
    # Send email logic
    pass

Support

License

This template is released under the MIT License. See LICENSE for details.

Project Structure

alembic/:Database migration files
app/:Main application directory
app/api/:API route definitions
app/core/:Core configuration and security
app/crud/:Database CRUD operations
app/main.py:FastAPI application entry point
app/models/:SQLAlchemy database models
app/schemas/:Pydantic schemas
docker-compose.yml:Docker services configuration
requirements.txt:Python dependencies
tests/:Test suite

Customization Options

Authentication System

Include JWT-based authentication with user management

Database Integration

Set up SQLAlchemy with PostgreSQL or SQLite

Docker Configuration

Include Docker and docker-compose setup

Background Tasks

Add Celery for background job processing

API Rate Limiting

Include rate limiting middleware

Deployment Options

Heroku

Deploy to Heroku with PostgreSQL addon

  1. Install Heroku CLI
  2. Create new Heroku app
  3. Add PostgreSQL addon
  4. Configure environment variables
  5. Deploy with git push

Docker

Deploy using Docker containers

  1. Build Docker image
  2. Configure environment variables
  3. Run with docker-compose
  4. Set up reverse proxy (nginx)

AWS Lambda

Serverless deployment with Mangum

  1. Install Mangum adapter
  2. Configure serverless.yml
  3. Deploy with Serverless Framework

Similar Templates