Area | Focus |
---|---|
Edge cases | Re-registering with same email, missing fields |
Security | Rate limiting, CAPTCHA, timing attacks |
Scalability | Async DB writes, background tasks for emails |
Maintainability | Is your logic testable and reusable? |
Clean architecture | Are you separating layers (API, service, DB)? |
Error handling | Are you raising proper exceptions with status codes? |
Auditing | Should you log registrations? Add metrics? |
β β βββ init.py β β βββ v1/ # API version 1 β β βββ init.py β β βββ user.py # User endpoints (register, login, profile) β βββ core/ # Core functionality and utilities β β βββ init.py β β βββ config.py # Configuration settings β β βββ security.py # JWT tokens, password hashing β β βββ validate.py # Input validation utilities β βββ models/ # Database models (Beanie ODM) β β βββ init.py β β βββ user.py # User document model β βββ schemas/ # Pydantic schemas (request/response) β β βββ init.py β β βββ auth.py # Authentication schemas β β βββ user.py # User request/response schemas β βββ services/ # Business logic layer β βββ init.py β βββ user_service.py # User business logic βββ tests/ # Test suite β βββ init.py β βββ test_api.py # API endpoint tests β βββ test_models.py # Database model tests β βββ test_schemas.py # Schema validation tests β βββ test_validate.py # Validation utility tests βββ docker-compose.yml # Docker services configuration βββ Dockerfile # Application container βββ requirements.txt # Python dependencies βββ pytest.ini # Test configuration βββ .env.example # Environment variables template βββ README.md # This file
## π Quick Start
### Prerequisites
- Python 3.8+
- MongoDB 4.4+
- Docker & Docker Compose (optional)
### Installation
1. **Clone the repository**
```bash
git clone <repository-url>
cd python-fastapi-service
-
Create 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
cp .env.example .env # Edit .env with your configuration
-
Start MongoDB (if not using Docker)
# Using Docker docker run -d -p 27017:27017 --name mongodb mongo:latest # Or install MongoDB locally # https://docs.mongodb.com/manual/installation/
-
Run the application
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# Start all services (app + MongoDB)
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
Once the server is running, visit:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- OpenAPI JSON: http://localhost:8000/openapi.json
Method | Endpoint | Description | Auth Required |
---|---|---|---|
POST | /users/register |
Register new user | β |
POST | /users/login |
User login | β |
GET | /users/me |
Get current user profile | β |
GET | /users/ |
List users (admin only) | β |
Register User
curl -X POST "http://localhost:8000/users/register" \
-H "Content-Type: application/json" \
-d '{
"username": "john_doe",
"email": "[email protected]",
"password": "SecurePass123!"
}'
Login User
curl -X POST "http://localhost:8000/users/login" \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "SecurePass123!"
}'
pytest
# Unit tests only
pytest tests/test_validate.py -v
# API tests only
pytest tests/test_api.py -v
# With coverage
pytest --cov=app tests/
test_validate.py
: Validation utility teststest_schemas.py
: Pydantic schema teststest_models.py
: Database model teststest_api.py
: API endpoint integration tests
Create a .env
file with the following variables:
# Database
MONGO_URL=mongodb://localhost:27017
DATABASE_NAME=fastapi_service
# Security
SECRET_KEY=your-super-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# Application
APP_NAME=FastAPI Service
APP_VERSION=1.0.0
DEBUG=false
# CORS
ALLOWED_ORIGINS=["http://localhost:3000", "http://localhost:8080"]
- Minimum 8 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one number
- At least one special character
- No common weak patterns
- Account locking after 5 failed login attempts
- JWT token-based authentication
- Password hashing with bcrypt
- Email validation with deliverability checks
- Comprehensive Pydantic schemas
- Custom validation functions
- SQL injection prevention
- XSS protection
- Separation of Concerns: Clear separation between API, business logic, and data layers
- Dependency Inversion: High-level modules don't depend on low-level modules
- Single Responsibility: Each module has a single, well-defined purpose
- Open/Closed Principle: Open for extension, closed for modification
- API Layer (
app/api/
): HTTP request/response handling, routing - Schema Layer (
app/schemas/
): Data validation and serialization - Service Layer (
app/services/
): Business logic and orchestration - Model Layer (
app/models/
): Data persistence and database operations - Core Layer (
app/core/
): Shared utilities and configuration
{
"_id": ObjectId,
"name": str,
"email": str, # Unique, indexed
"hashed_password": str,
"active": bool,
"role": str,
"created_at": datetime,
"updated_at": datetime,
"last_login": datetime,
"login_attempts": int,
"locked_until": datetime,
"phone": str,
"address": str,
"profile_picture_url": str,
"cover_picture_url": str
}
email
: Unique index for fast user lookupactive
: Index for filtering active usersrole
: Index for role-based queriescreated_at
: Index for sorting by creation date
- Set strong
SECRET_KEY
in production - Configure proper MongoDB connection string
- Set
DEBUG=false
- Configure CORS origins
- Set up SSL/TLS certificates
- Configure logging levels
- Set up monitoring and health checks
- Configure backup strategy
# Build production image
docker build -t fastapi-service:latest .
# Run with production settings
docker run -d \
--name fastapi-service \
-p 8000:8000 \
--env-file .env.production \
fastapi-service:latest
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Make your changes
- Add tests for new functionality
- Ensure all tests pass (
pytest
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
- Follow PEP 8 guidelines
- Use type hints
- Write docstrings for functions and classes
- Maintain test coverage above 90%
- Use meaningful variable and function names
- Create schema in
app/schemas/
- Add business logic in
app/services/
- Create API endpoint in
app/api/v1/
- Write tests in
tests/
- Update documentation
For schema changes:
- Update model in
app/models/
- Create migration script if needed
- Test with sample data
- Update tests
MongoDB Connection Issues
# Check if MongoDB is running
docker ps | grep mongo
# Check connection
mongo mongodb://localhost:27017
Import Errors
# Ensure you're in the virtual environment
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
Test Failures
# Run tests with verbose output
pytest -v
# Run specific test
pytest tests/test_api.py::TestUserRegistrationAPI::test_successful_registration -v
- FastAPI Documentation
- Beanie ODM Documentation
- Pydantic Documentation
- MongoDB Documentation
- pytest Documentation
This project is licensed under the MIT License - see the LICENSE file for details.
- Your Name - Initial work - YourGitHub
- FastAPI team for the amazing framework
- MongoDB team for the robust database
- Python community for excellent libraries
Built with β€οΈ using FastAPI, MongoDB, and Python