This is a sample FastAPI application that connects to MongoDB and provides CRUD (Create, Read, Update, Delete) operations for user data. The application is designed with best practices in mind, incorporating:
- Connection Pooling with MongoDB
- Pydantic Models for data validation
- Object-Oriented Programming (OOP) principles
- Dataclasses
- Typing and AsyncIO usage
- Custom Logging with correlation IDs
- Middleware usage
- CORS Settings for security
- Unit Testing
- GitHub Actions Workflow for automated testing
- Docker Setup with multi-stage builds and non-root user
- Health Check Endpoint
- Directory Structure
- Features
- Getting Started
- Running the Application
- API Documentation
- Running Tests
- Docker Setup Details
- Logging and Correlation IDs
- Middleware
- GitHub Actions CI/CD
- Contributing
├── app/
│ ├── main.py
│ ├── core/
│ │ ├── config.py
│ │ ├── security.py
│ ├── db/
│ │ └── connectors.py
│ ├── middleware/
│ │ └── correlation_id.py
│ ├── models/
│ │ └── users.py
│ ├── routers/
│ │ └── users.py
│ └── utils/
│ └── logger.py
├── tests/
│ └── test_user.py
├── .github/
│ └── workflows/
│ └── ci.yml
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
├── .env (optional)
├── README.md
- Create User: Add a new user to the database
- Delete User: Remove an existing user
- List Users: Retrieve a list of all users
- Update User: Modify details of an existing user
- Health Check Endpoint: Verify the application's status
- Python 3.12
- Docker and Docker Compose (if running with Docker)
- MongoDB (if running without Docker)
- Git (for cloning the repository)
- Clone the Repository
git clone https://github.com/yourusername/fastapi-user-crud.git
cd fastapi-user-crud
- Set Up Environment Variables
Create a .env
file in the root directory (optional, required if you need to override default settings):
MONGODB_URI=mongodb://localhost:27017
MONGODB_DB=testdb
- Install Dependencies (if running without Docker)
pip install -r requirements.txt
- Build and Run the Containers
docker compose up --build
- Access the API
- Interactive API Docs: http://localhost:8000/docs
- Redoc: http://localhost:8000/redoc
- Ensure MongoDB is Running
- Install MongoDB and start the service.
- Run the Application
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
- Access the API
- API Base URL: http://localhost:8000
- Interactive API Docs: http://localhost:8000/docs
The application provides an OpenAPI specification accessible via Swagger UI.
- Swagger UI: http://localhost:8000/docs
- Redoc: http://localhost:8000/redoc
GET /healthcheck
Response: { "status": "ok" }
POST /users
Body:
{
"name": "John Doe",
"email": "[email protected]",
"password": "securepassword"
}
Response:
{
"id": "user_id",
"name": "John Doe",
"email": "[email protected]"
}
GET /users
Response:
[
{
"id": "user_id",
"name": "John Doe",
"email": "[email protected]"
},
...
]
GET /users/{user_id}
Response:
{
"id": "user_id",
"name": "John Doe",
"email": "[email protected]"
}
PUT /users/{user_id}
Body:
{
"name": "John Smith",
"email": "[email protected]"
}
Response:
{
"id": "user_id",
"name": "John Smith",
"email": "[email protected]"
}
DELETE /users/{user_id}
Response:
{
"status": "deleted"
}
Unit tests are located in the tests/
directory.
Run Tests:
python -m unittest discover -s tests
Tests will automatically run on each push or pull request via GitHub Actions.
The application uses a multi-stage Docker build for efficiency and security.
- Multi-stage Builds: Reduce the final image size by building dependencies separately
- Security Best Practices:
- Runs the application as a non-root user (appuser)
- Minimizes the number of layers and removes unnecessary packages
- Docker Compose: Orchestrates the application and MongoDB services
- Stage 1 (Builder): Installs dependencies and builds wheels
- Stage 2 (Final Image):
- Copies the built wheels
- Installs the application
- Sets up a non-root user
- Exposes port 8000
To run the application behind Nginx, you can modify the Docker Compose setup or add a new service in the docker-compose.yml
.
- Custom Logger: Configured to include correlation IDs in log messages
- Correlation IDs: Unique identifier for each request, useful for tracing and debugging
Located in app/utils/logger.py
:
- Format:
%(asctime)s - %(name)s - %(levelname)s - %(correlation_id)s - %(message)s
Implemented in app/middleware/correlation_id.py
:
- Adds a unique X-Request-ID header to each response
- Accessible throughout the application via context variables
- Correlation ID Middleware: Injects a unique ID into each request
- CORS Middleware: Configured to allow cross-origin requests (adjust settings for production)
Middleware is added in app/main.py
:
app.add_middleware(CorrelationIdMiddleware)
Automated testing is set up using GitHub Actions.
Located at .github/workflows/ci.yml
.
Triggers:
- On push to the main branch
- On pull requests to the main branch
Jobs:
- Set up Python environment
- Install dependencies
- Run unit tests
Contributions are welcome! Please follow these steps:
-
Fork the Repository
-
Create a Feature Branch
git checkout -b feature/your-feature-name
- Commit Your Changes
git commit -m "Add your message here"
- Push to Your Branch
git push origin feature/your-feature-name
- Open a Pull Request