A production-ready FastAPI application demonstrating best practices for building high-performance REST APIs with automatic documentation, type safety, and modern Python features.
- Fast Performance: Built on Starlette and Pydantic for blazing-fast request handling
- Automatic Documentation: Interactive API docs with Swagger UI and ReDoc
- Type Safety: Full type hints with Pydantic models for request/response validation
- Async Support: Async/await for high concurrency
- Database Integration: SQLAlchemy ORM with async support
- Authentication: JWT-based authentication
- Testing: Comprehensive test suite with pytest
- Docker Ready: Multi-stage Dockerfile for production deployment
- Python 3.11+
- Docker (optional, for containerized deployment)
- Clone the repository:
git clone https://github.com/ry-ops/building-rest-api-fastapi.git
cd building-rest-api-fastapi- Create a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies:
pip install -r requirements.txt- Run the development server:
uvicorn app.main:app --reload- Access the API:
- API: http://localhost:8000
- Interactive docs: http://localhost:8000/docs
- Alternative docs: http://localhost:8000/redoc
docker build -t fastapi-app .
docker run -p 8000:8000 fastapi-app.
├── app/
│ ├── __init__.py
│ ├── main.py # Application entry point
│ ├── config.py # Configuration management
│ ├── database.py # Database setup
│ ├── dependencies.py # Dependency injection
│ ├── models/ # SQLAlchemy models
│ │ ├── __init__.py
│ │ └── user.py
│ ├── schemas/ # Pydantic schemas
│ │ ├── __init__.py
│ │ ├── user.py
│ │ └── token.py
│ ├── routers/ # API route handlers
│ │ ├── __init__.py
│ │ ├── auth.py
│ │ └── users.py
│ └── utils/ # Utility functions
│ ├── __init__.py
│ ├── security.py
│ └── validation.py
├── tests/
│ ├── __init__.py
│ ├── test_main.py
│ ├── test_auth.py
│ └── test_users.py
├── examples/
│ ├── client.py # Example API client
│ └── load_test.py # Load testing script
├── documentation/
│ ├── API.md # API endpoint documentation
│ ├── DEPLOYMENT.md # Deployment guide
│ └── DEVELOPMENT.md # Development guide
├── requirements.txt
├── requirements-dev.txt
├── Dockerfile
├── docker-compose.yml
├── .env.example
└── README.md
POST /auth/register- Register a new userPOST /auth/login- Login and receive JWT tokenPOST /auth/refresh- Refresh access token
GET /users/me- Get current user profilePUT /users/me- Update current user profileGET /users/{user_id}- Get user by ID (admin only)GET /users- List all users (admin only)
GET /health- Health check endpointGET /- API information
Copy .env.example to .env and configure:
# Application
APP_NAME=FastAPI Application
APP_VERSION=1.0.0
DEBUG=False
# Database
DATABASE_URL=postgresql+asyncpg://user:password@localhost/dbname
# Security
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# CORS
CORS_ORIGINS=["http://localhost:3000"]# Run all tests
pytest
# Run with coverage
pytest --cov=app tests/
# Run specific test file
pytest tests/test_users.py# Format code
black app/ tests/
# Sort imports
isort app/ tests/
# Type checking
mypy app/
# Linting
ruff check app/ tests/# Create a new migration
alembic revision --autogenerate -m "Description"
# Apply migrations
alembic upgrade head
# Rollback migration
alembic downgrade -1from examples.client import APIClient
# Initialize client
client = APIClient(base_url="http://localhost:8000")
# Register a user
user = client.register(
email="user@example.com",
password="securepassword",
full_name="John Doe"
)
# Login
token = client.login(email="user@example.com", password="securepassword")
# Get current user
profile = client.get_current_user(token)import requests
# Register
response = requests.post(
"http://localhost:8000/auth/register",
json={
"email": "user@example.com",
"password": "securepassword",
"full_name": "John Doe"
}
)
# Login
response = requests.post(
"http://localhost:8000/auth/login",
data={
"username": "user@example.com",
"password": "securepassword"
}
)
token = response.json()["access_token"]
# Get profile
response = requests.get(
"http://localhost:8000/users/me",
headers={"Authorization": f"Bearer {token}"}
)See documentation/DEPLOYMENT.md for detailed deployment instructions including:
- Docker deployment
- Kubernetes deployment
- Cloud platform deployment (AWS, GCP, Azure)
- Environment configuration
- SSL/TLS setup
- Monitoring and logging
FastAPI is one of the fastest Python frameworks available:
- Handles 10,000+ requests/second on modest hardware
- Sub-millisecond response times for simple endpoints
- Efficient async I/O for database and external API calls
- Automatic JSON serialization with Pydantic
See examples/load_test.py for performance benchmarking.
- Password hashing with bcrypt
- JWT token-based authentication
- CORS middleware configured
- SQL injection protection via SQLAlchemy
- Input validation with Pydantic
- Rate limiting (recommended for production)
- API Documentation - Detailed API endpoint reference
- Development Guide - Development best practices
- Deployment Guide - Production deployment instructions
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License - see LICENSE file for details
For issues and questions:
- Check the API Documentation
- Review existing GitHub issues
- Open a new issue with detailed information