Modern, production-ready FastAPI application with MongoDB integration, featuring clean architecture, comprehensive testing, and Docker support.
- FastAPI - Modern, fast web framework for building APIs with automatic OpenAPI documentation
- MongoDB - NoSQL database with Motor async driver for high-performance data operations
- Pydantic V2 - Data validation using Python type annotations with automatic serialization
- Clean Architecture - Repository pattern, service layer, and dependency injection for maintainable code
- Docker Support - Multi-stage builds for production and docker-compose for development
- Testing - Comprehensive test suite with pytest, unit and integration tests
- Type Safety - Full type hints with mypy validation for better IDE support and fewer bugs
- Code Quality - Black formatter, Ruff linter, and pre-commit hooks for consistent code style
- CI/CD - GitHub Actions for automated testing, building, and deployment
- Security - Security headers middleware, environment validation, and vulnerability scanning
- Health Checks - Ready and liveness probes for Kubernetes deployments
- CRUD Operations - Complete Create, Read, Update, Delete functionality with async support
- Error Handling - Comprehensive exception handling with custom error responses
- Documentation - Auto-generated API docs, contributing guide, and changelog
app/
βββ api/ # API endpoints and dependencies
β βββ api_v1/ # API version 1
β β βββ endpoints/ # Route handlers
β β βββ api.py # API router
β βββ deps.py # Dependency injection
βββ core/ # Core functionality
β βββ settings.py # Application settings
β βββ exceptions.py # Custom exceptions
βββ db/ # Database configuration
β βββ database.py # MongoDB connection
βββ models/ # Database models
βββ schemas/ # Pydantic schemas
βββ services/ # Business logic
βββ repositories/ # Data access layer
βββ main.py # Application entry point
- Python 3.11+
- MongoDB 7.0+ (or Docker)
- pip or poetry
git clone https://github.com/rafeekpro/FastApiWithMongoStarter.git
cd FastApiWithMongoStarter# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt# Copy example environment file
cp .env.example .env
# Edit .env with your configuration
# Generate a secure SECRET_KEY:
python -c "import secrets; print(secrets.token_urlsafe(32))"# Start all services (app, MongoDB, Mongo Express)
docker-compose up -d
# View logs
docker-compose logs -f app
# Stop services
docker-compose downThe application will be available at:
- API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
- Mongo Express: http://localhost:8081 (admin/admin)
# Make sure MongoDB is running locally
# Update .env with your MongoDB connection details
# Run the application
uvicorn app.main:app --reload
# Or with custom host/port
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reloadOnce the application is running, you can access:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- OpenAPI Schema: http://localhost:8000/openapi.json
GET /api/v1/movies- List all movies with paginationGET /api/v1/movies/{movie_id}- Get movie by IDGET /api/v1/movies/slug/{slug}- Get movie by slugPOST /api/v1/movies- Create a new moviePUT /api/v1/movies/{movie_id}- Update a movieDELETE /api/v1/movies/{movie_id}- Delete a movie
GET /health- Health checkGET /ready- Readiness probe
pip install -r requirements.txt
# or
pip install -e ".[dev]"# Run all tests
pytest
# Run with coverage
pytest --cov=app --cov-report=html
# Run specific test file
pytest tests/unit/test_schemas.py
# Run with verbose output
pytest -v# Format code
ruff format .
# Lint code
ruff check . --fix
# Type checking
mypy app
# Install pre-commit hooks
pre-commit install
# Run pre-commit on all files
pre-commit run --all-files# Build production image
docker build -t fastapi-mongodb-app .
# Run production container
docker run -d \
-p 8000:8000 \
-e MONGODB_URL="mongodb://user:pass@host:27017/db" \
-e SECRET_KEY="your-production-secret-key" \
--name fastapi-app \
fastapi-mongodb-appThe project includes automated CI/CD pipelines:
-
CI Pipeline - Runs on every push and PR:
- Linting with Black and Ruff
- Type checking with mypy
- Unit and integration tests
- Security scanning
- Docker build test
-
CD Pipeline - Runs on release:
- Builds multi-platform Docker images
- Pushes to Docker Hub
- Optional deployment to cloud providers
Required for production:
SECRET_KEY- Secret key for security (generate a strong one!)MONGODB_URL- MongoDB connection stringALLOWED_HOSTS- Comma-separated list of allowed hosts
Optional:
DEBUG- Set to false in production (default: false)PROJECT_NAME- Application nameMAX_CONNECTIONS_COUNT- MongoDB max connectionsMIN_CONNECTIONS_COUNT- MongoDB min connections
{
"_id": ObjectId,
"name": String,
"casts": [String],
"genres": [String],
"year": Number,
"slug": String,
"classification": [
{
"country": String,
"value": String
}
],
"created_at": DateTime,
"updated_at": DateTime
}slug- Unique indexname- Text index for searchyear- Regular indexgenres- Regular index
This project is actively maintained and production-ready. It follows best practices for:
- β Clean Architecture
- β Test-Driven Development
- β Continuous Integration/Deployment
- β Security Best Practices
- β Documentation Standards
- β Code Quality Standards
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
See CONTRIBUTING.md for detailed development setup instructions.
This project is licensed under the MIT License - see the LICENSE file for details.
- Inspired by fastapi-mongodb-realworld-example-app
- Built with FastAPI
- Database powered by MongoDB