Python FastAPI MongoDB CRUD Application end-to-end example
This project is a web application built with FastAPI and MongoDB. It provides a RESTful API for managing users and integrates Docker for containerization. The application is designed following best practices for a clean architecture, making it easy to maintain and extend. It is a simple CRUD application that allows to create, read, update, and delete.
Also, this project use pydantic, motor, beanie, and docker.
- FastAPI: A modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints.
- MongoDB: A NoSQL database for storing user data.
- Uvicorn: Uvicorn is an ASGI web server implementation for Python.
- Pydantic: Pydantic is the most widely used data validation library for Python.
- Motor: Motor presents a coroutine-based API for non-blocking access to MongoDB from Tornado or asyncio.
- Beanie: Beanie - is an asynchronous Python object-document mapper (ODM) for MongoDB. Data models are based on Pydantic.
- Docker: Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers.
- Oauth2: OAuth2 with Password (and hashing), Bearer with JWT tokens.
- Python 3.10+
- Docker
- Docker Compose
- MongoDB
- Git
- FastAPI
- Pydantic
- Motor
- Beanie
- Uvicorn
- change the environment values with your own values in the .env.dev and .env.prod files
- Find the change-me and replace it with your own values in source code
- Clone the repository
git clone https://github.com/cevheri/pyfapi.git
- Change the directory
cd pyfapi
- create a virtual environment
python3 -m venv venv
- Activate the virtual environment
source venv/bin/activate
- Install the dependencies
pip install -r requirements.txt
- Create a .env file in the root directory and add the following environment variables
cp .env.default .env.dev
cp .env.default .env.prod
- Run the application on local machine (development mode)
uvicorn app.main:app --host 0.0.0.0 --port 8000 --env-file .env.dev
- Run the application production mode with python
uvicorn app.main:app --host 0.0.0.0 --port 8000 --env-file .env.prod
python3 main_dev.py
python3 main_prod.py
- docker-compose.yaml file has three services: app, mongo, and mongo-express.
docker-compose up --build
- Open your browser and go to root url http://localhost:8000 to access the FastAPI application.
- Open your browser and go to http://localhost:8000/api/v1/docs to access the Swagger UI.
- Open your browser and go to http://localhost:8081 to access the MongoDB Express.
Security is a critical aspect of any application. This project uses OAuth2 with Password (and hashing), Bearer with JWT tokens.
- Security settings are defined in the app/security directory.
- Security middleware is defined in the app/middleware/security.py file.
- if you want to allow the endpoint without authentication, you can add the endpoint to the env file like this:
SECURITY_ALLOWED_PATHS=/api/v1/public/products
... | ... |
---|---|
-- app | Main application directory |
-- app/api | API endpoints and routes |
-- app/config | Configuration settings |
-- app/entity | Database models |
-- app/repository | Data access layer |
-- app/service | Business logic layer |
-- app/schema | API models |
-- app/security | Security settings |
-- app/utils | Utility functions |
-- app/main.py | Main application file |
-- tests | Test cases |
-- .env.default | Default environment variables |
... | ... |
This project use a clean architecture, separation of concerns, and single responsibility principles. If you want to add a new feature, you need to follow the structure of the project.
For example, you need product management features. You can follow the steps below.
- product_api.py: API endpoints and routes, request, and response models, and API logic. OpenAPI documentation, and Swagger UI.
- product_service.py: Business logic layer
- product_dto.py: API models for API endpoints
- product_repository.py: Data access layer for database operations
- product.py: Database models for MongoDB (Beanie ODM)
- Create a new file in the app/schema like product_dto.py (use the existing files as a reference user_dto.py) Classes: ProductDTO, ProductCreate, ProductUpdate
- Create a new file in the app/api directory like product_api.py (use the existing files as a reference user_api.py)
- Edit the app/api/init.py file and add the new route
- Create a new file in the app/service like product_service.py (use the existing files as a reference user_service.py) Classes: ProductService
This project use Beanie ODM for MongoDB. You can create a new entity for the database.
- Create a new file in the app/entity like product.py (use the existing files as a reference user.py) Classes: Product
- Edit the app/entity/init.py file and add the new entity
- Edit the app/conf/env/db_config.py file and add the new entity init_beanie()
- Create a new file in the app/repository like product_repository.py (use the existing files as a reference user_repository.py) Classes: ProductRepository
Unit tests and integration tests are essential for ensuring the quality of the application. This project uses pytest for testing.
- Folder structure
... | ... |
---|---|
test | Test cases |
tests/api | API endpoints and routes tests |
tests/service | Business logic layer tests |
tests/repository | Data access layer tests |
- Run all tests
PYTHONPATH=. pytest
Sample result :
22 passed in 0.52s
This FastAPI MongoDB application is structured to provide a robust and scalable API solution. By leveraging Docker and CI/CD practices, the application can be easily deployed and maintained.
Feel free to contribute to this project by submitting issues or pull requests!