This is a ready-to-use project template for building FastAPI applications with MongoDB as the database. It's designed to help you get started quickly with a clean architecture, pre-configured settings, and best practices for scalability and maintainability.
fastapi-mongodb/
├── app/
│ ├── core/ # Core configuration and utilities
│ │ ├── config.py # Environment variables and configuration
│ │ ├── constants.py # Application constants
│ │ ├── jwt.py # JWT token handling
│ │ ├── logger.py # Logging configuration
│ │ └── security.py # Security utilities
│ ├── database/
│ │ ├── init-db.js # MongoDB initialization script
│ │ └── mongodb.py # MongoDB connection and configuration
│ ├── middlewares/
│ │ └── logging.py # Logging middleware
│ ├── repositories/
│ │ └── user.py # User data access layer
│ ├── routers/
│ │ ├── auth.py # Authentication endpoints
│ │ └── me.py # Current user endpoints
│ ├── schemas/
│ │ └── user.py # Pydantic user schemas
│ ├── services/
│ │ ├── auth.py # Authentication business logic
│ │ └── user.py # User business logic
│ └── main.py # Application entry point
├── docker/
│ └── fastapi/
│ └── Dockerfile # FastAPI Docker image
├── tests/
│ ├── conftest.py # Pytest configuration
│ ├── test_auth.py # Authentication tests
│ └── test_me.py # User endpoints tests
├── .env.template # Environment variables template
├── docker-compose.yaml # Docker Compose configuration
├── pyproject.toml # Project dependencies and configuration
├── pytest.toml # Pytest configuration
└── ruff.toml # Linter configuration
- JWT-based authentication.
- Refresh token.
- Middleware.
- Tests with pytest.
- Log handler.
- Indexes to MongoDB.
- Email verification.
- Handler exceptions.
- Programming language.
- Python framework for web applications to expose the API.
- NoSQL database.
Install Docker following the instructions for your operating system:
Clone the repository:
git clone https://github.com/CarlosAndreo/fastapi-mongodb.git
cd fastapi-mongodbCreate the .env file from the template:
cp .env.template .envNote
Edit the .env file and update the values according to your needs. Make sure to set a strong SECRET_KEY (you can generate one with openssl rand -hex 32).
Build the Docker image:
docker compose buildRun the Docker container:
docker compose up -dThe application will be available at http://localhost:8000/api/v1/docs.
The mongo-express UI will be available at http://localhost:8081.
Warning
When run the tests, the database is cleaned.
To test the application, access to the fastapi container:
docker exec -it fastapi-mongodb shFinally, execute:
uv run pytest