A production-ready FastAPI application with MongoDB using the PyMongo driver (Motor for async operations).
- ✅ FastAPI 0.117+ with async/await
- ✅ MongoDB with Motor (async PyMongo driver)
- ✅ Pydantic v2 for data validation
- ✅ CRUD operations for User resource
- ✅ RESTful API design
- ✅ Connection pooling and error handling
- ✅ CORS middleware
- ✅ Environment-based configuration
- ✅ Type hints throughout
- ✅ Proper HTTP status codes
- ✅ API documentation (Swagger/ReDoc)
project-name/
├── app/
│ ├── __init__.py
│ ├── config/
│ │ ├── __init__.py
│ │ ├── database.py # Database connection management
│ │ └── settings.py # Application settings
│ ├── middleware/
│ │ ├── __init__.py
│ │ └── error_handler.py # Error handling middleware
│ ├── models/
│ │ ├── __init__.py
│ │ └── user.py # User model with CRUD operations
│ ├── routers/
│ │ ├── __init__.py
│ │ └── users.py # User API endpoints
│ └── schemas/
│ ├── __init__.py
│ └── user.py # Pydantic schemas
├── .env.example # Example environment variables
├── .gitignore
├── requirements.txt # Python dependencies
├── README.md
└── main.py # Application entry point
- Python 3.11+
- MongoDB 4.4+
- Clone the repository
git clone <repository-url>
cd test-prompt-fastapi- Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies
pip install -r requirements.txt- Set up environment variables
Copy .env.example to .env and update the values:
cp .env.example .envEdit .env:
DEBUG=false
MONGODB_URI=mongodb://localhost:27017
DATABASE_NAME=app_db
CORS_ORIGINS=["http://localhost:3000"]- Start MongoDB
Make sure MongoDB is running on your system. If using Docker:
docker run -d -p 27017:27017 --name mongodb mongo:latestpython main.pyOr with uvicorn directly:
uvicorn main:app --reload --host 0.0.0.0 --port 8000uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4The application will be available at:
- API: http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
GET /- Welcome messageGET /health- Health check endpoint
All user endpoints are prefixed with /api/v1/users
POST /api/v1/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com"
}Response (201 Created):
{
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z"
}GET /api/v1/users?skip=0&limit=100Response (200 OK):
[
{
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z"
}
]GET /api/v1/users/{user_id}Response (200 OK):
{
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z"
}PUT /api/v1/users/{user_id}
Content-Type: application/json
{
"name": "Jane Doe",
"email": "jane@example.com"
}Response (200 OK):
{
"id": "507f1f77bcf86cd799439011",
"name": "Jane Doe",
"email": "jane@example.com",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:05:00Z"
}DELETE /api/v1/users/{user_id}Response (200 OK):
{
"message": "User deleted successfully"
}{
"detail": "Invalid user ID format"
}{
"detail": "User not found"
}{
"detail": "Internal server error"
}curl -X POST "http://localhost:8000/api/v1/users" \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com"}'curl "http://localhost:8000/api/v1/users"curl "http://localhost:8000/api/v1/users/{user_id}"curl -X PUT "http://localhost:8000/api/v1/users/{user_id}" \
-H "Content-Type: application/json" \
-d '{"name": "Jane Doe"}'curl -X DELETE "http://localhost:8000/api/v1/users/{user_id}"The application uses Motor (async PyMongo) for MongoDB operations:
- Connection pooling with max 10 connections
- Automatic connection management via FastAPI lifespan events
- Proper error handling for connection failures
Pydantic v2 models ensure:
- Type safety
- Email validation
- Field constraints (min/max length)
- Automatic data serialization
Custom exception handlers for:
- MongoDB duplicate key errors
- Invalid ObjectId format
- General exceptions
- Modern Python with type hints
- Async/await syntax throughout
- FastAPI dependency injection
- Pydantic models for validation
- Create schema in
app/schemas/ - Create model in
app/models/ - Create router in
app/routers/ - Register router in
main.py
MIT License