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.
- Python - Programming language.
- FastAPI - Python framework for web applications to expose the API.
- MongoDB - 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 .env
Note
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 build
Run the Docker container:
docker compose up -d
The 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