A Python-based RESTful API built with Django showcasing modern Python development practices and CRUD operations for user management.
This project is part of a multi-language series demonstrating equivalent server implementations across different technologies. This Django version showcases:
- Django framework with Django REST Framework
- RESTful API design patterns
- Input validation with Django serializers
- Comprehensive testing with Django's testing framework
- Docker containerization
- Modern Python development practices
- Clean architecture with Django's MVC pattern
- Runtime: Python 3.8+
- Framework: Django 5.2.5
- Database: SQLite (default)
- Validation: Django serializers
- Testing: pytest with Django integration and comprehensive test coverage
- Package Management: pip with requirements.txt and pyproject.toml
- Code Quality: pylint with 10/10 rating across all modules
- Containerization: Docker & Docker Compose
- Python 3.8+ and pip
- OR Docker and Docker Compose
-
Clone and navigate to the project
git clone <repository-url> cd api-demo-django
-
Create and activate virtual environment
python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Run database migrations
python manage.py migrate
-
Start the development server
python manage.py runserver
-
Server is now running at
http://localhost:8000
-
Prerequisites
- Docker Desktop installed and running
- Docker Compose (included with Docker Desktop)
-
Clone and navigate to the project
git clone <repository-url> cd api-demo-django
-
Start with Docker Compose
docker-compose up --build
-
Access the application
- API Server:
http://localhost:8000 - Users API:
http://localhost:8000/users - Admin Interface:
http://localhost:8000/admin/(admin/admin)
- API Server:
-
What happens automatically
- β Container builds with Python 3.11 and dependencies
- β Database migrations run automatically
- β User store seeded with 10 sample users
- β
Admin superuser created (username:
admin, password:admin) - β Development server starts with hot reloading
-
Stop the container when done
docker-compose down
The API provides the following endpoints for user management:
http://localhost:8000
| Method | Endpoint | Description | Body Required |
|---|---|---|---|
GET |
/ |
Homepage | No |
GET |
/users |
Get all users | No |
POST |
/user |
Create a new user | Yes |
GET |
/user/:id |
Get user by ID | No |
PATCH |
/user/:id |
Update user by ID | Yes |
DELETE |
/user/:id |
Delete user by ID | No |
{
"id": "string (UUID)",
"firstName": "string",
"lastName": "string",
"email": "string",
"phone": "string",
"createdAt": "string (ISO date)",
"updatedAt": "string (ISO date)"
}1. Get all users:
curl http://localhost:8000/users2. Get a specific user:
curl http://localhost:8000/user/13. Create a new user:
curl -X POST http://localhost:8000/user \
-H "Content-Type: application/json" \
-d '{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"phone": "+1-555-555-1234"
}'4. Update a user:
curl -X PATCH http://localhost:8000/user/1 \
-H "Content-Type: application/json" \
-d '{
"firstName": "Jane",
"email": "jane.doe@example.com"
}'5. Delete a user:
curl -X DELETE http://localhost:8000/user/1Import the following collection or manually create requests:
- Base URL:
http://localhost:8000 - Set
Content-Type: application/jsonfor POST/PATCH requests - Use the endpoints listed above
api-demo-django/
βββ config/ # Django project configuration
β βββ __init__.py
β βββ settings.py # Django settings
β βββ urls.py # Main URL configuration
β βββ wsgi.py # WSGI configuration
β βββ asgi.py # ASGI configuration
βββ users/ # Django app for user operations
β βββ __init__.py # Python package marker
β βββ admin.py # Django admin configuration with User model
β βββ apps.py # App configuration with auto-seeding
β βββ migrations/ # Database migration files
β β βββ __init__.py
β βββ models.py # User data models with comprehensive docstrings
β βββ serializers.py # DRF serializers for validation and data transformation
β βββ store.py # In-memory data store with CRUD operations
β βββ tests/ # Comprehensive test suite
β β βββ test_serializers.py # Unit tests for serializers
β β βββ test_users_api.py # API integration tests
β βββ urls.py # App-specific URL patterns
β βββ views.py # API views using Django REST Framework
βββ manage.py # Django management script
βββ requirements.txt # Python dependencies
βββ pyproject.toml # pytest configuration and project metadata
βββ conftest.py # pytest fixtures and test configuration
βββ Dockerfile # Docker image definition
βββ docker-compose.yml # Development Docker setup
βββ docker-compose.prod.yml # Production Docker setup
βββ entrypoint.sh # Container initialization script
βββ .dockerignore # Docker build context exclusions
βββ DOCKER_README.md # Detailed Docker documentation
The users/ directory contains a complete Django app that implements user management functionality:
π store.py: In-memory data store
- Contains all CRUD operations for user management
- Pre-seeded with 10 sample users for testing
- Uses Python dictionaries to simulate database records
- Implements UUID-based user identification
- Provides functions:
list_users(),get_user(),create_user(),update_user(),delete_user()
π serializers.py: Data validation and transformation
UserCreateSerializer: Validates required fields for new users (firstName, email)UserUpdateSerializer: Validates optional fields for user updates- Uses Django REST Framework serializers for automatic validation
- Handles email validation and field length constraints
π― views.py: API endpoints implementation
UsersListView: GET/users- Returns all usersUserCreateView: POST/user- Creates a new userUserDetailView: GET/PATCH/DELETE/user/<id>- User-specific operations- Uses Django REST Framework's APIView for clean request/response handling
- Implements proper HTTP status codes (200, 201, 404, 204)
π£οΈ urls.py: URL routing configuration
- Maps HTTP endpoints to view classes
- Supports UUID-based user identification in URLs
- Clean RESTful URL patterns
π§ͺ tests/: Comprehensive test suite
test_serializers.py: Unit tests for UserCreateSerializer and UserUpdateSerializertest_users_api.py: Integration tests for all API endpoints- Uses pytest with Django integration for modern testing practices
- Includes API client fixtures and test markers for organization
- Request β Django URL dispatcher (
urls.py) - Routing β Appropriate view class (
views.py) - Validation β DRF serializers (
serializers.py) - Processing β In-memory store operations (
store.py) - Response β JSON data with proper HTTP status codes
This project uses pytest with Django integration for comprehensive testing.
Run all tests:
pytestRun tests with verbose output:
pytest -vRun specific test files:
pytest users/tests/test_serializers.py
pytest users/tests/test_users_api.pyRun tests with markers:
pytest -m api # Run only API integration tests
pytest -m unit # Run only unit testsRun tests with coverage report:
pip install pytest-cov
pytest --cov=users --cov-report=htmlpython manage.py runserver # Start development server
python manage.py migrate # Apply database migrations
python manage.py makemigrations # Create new migrations
pytest # Run tests (recommended)
python manage.py test # Run tests (Django native)
python manage.py shell # Open Django shell
python manage.py createsuperuser # Create admin user
python manage.py collectstatic # Collect static files
pylint users/ # Check code qualitydocker-compose up --build # Build and start container (recommended)
docker-compose up # Start container (if already built)
docker-compose up -d # Start container in detached mode
docker-compose down # Stop and remove container
docker-compose logs web # View container logs
docker-compose ps # Show running containers# Run Django management commands in container
docker-compose exec web python manage.py migrate
docker-compose exec web python manage.py createsuperuser
docker-compose exec web python manage.py shell
docker-compose exec web python manage.py test
# Access container shell
docker-compose exec web bash
# User store operations
docker-compose exec web python manage.py shell -c "
from users.store import reset_and_seed
reset_and_seed()
print('User store reset and reseeded')
"# Use production configuration
docker-compose -f docker-compose.prod.yml up --build
# Build without cache
docker-compose build --no-cache# Clean restart
docker-compose down
docker-compose build --no-cache
docker-compose up
# Check if Docker daemon is running
docker info
# Start Docker Desktop (macOS)
open -a DockerThis project includes a complete Docker setup optimized for both development and production:
- Base Image: Python 3.11 slim for smaller image size
- Non-root User: Security-focused container with dedicated app user
- Hot Reloading: Volume mounting for live code changes in development
- Auto-initialization: Automatic database setup and user store seeding
- Health Checks: Built-in Django development server monitoring
- Development (
docker-compose.yml): Volume mounting, debug mode, hot reloading - Production (
docker-compose.prod.yml): Gunicorn WSGI server, optimized settings
The entrypoint.sh script automatically handles:
- π Database migrations for Django admin functionality
- π± User store seeding with 10 sample users
- π€ Admin superuser creation (admin/admin)
- π Application startup
Docker Configuration/
βββ Dockerfile # Multi-stage build optimized for Python
βββ docker-compose.yml # Development with volume mounting
βββ docker-compose.prod.yml # Production with Gunicorn
βββ entrypoint.sh # Initialization and setup script
βββ .dockerignore # Build context optimization
βββ DOCKER_README.md # Comprehensive Docker documentation
For detailed Docker documentation, see DOCKER_README.md.
- RESTful API Design: Proper HTTP methods and status codes
- Input Validation: Django REST Framework serializers for request validation
- Error Handling: DRF exception handling with proper HTTP status codes
- Type Safety: Python type hints throughout the codebase
- Modern Testing: pytest with Django integration, fixtures, and test markers
- Code Quality: 10/10 pylint rating across all modules with comprehensive docstrings
- Test Coverage: Unit tests for serializers and integration tests for API endpoints
- Containerization: Complete Docker setup with development and production configurations
- In-Memory Storage: Custom store module for demonstration purposes
- Separation of Concerns: Clean Django architecture with views, serializers, and data layer
- Documentation: Comprehensive docstrings following Python standards
This demo uses in-memory storage implemented in users/store.py for simplicity. Key features:
- No Database Required: Uses Python lists and dictionaries to store data
- Pre-seeded Data: Automatically loads 10 sample users on first access
- Session Persistence: Data persists during the application session
- Reset on Restart: All data resets when the server restarts
- UUID Identification: Each user has a unique UUID identifier
- Realistic Data: Sample users include realistic names, emails, and phone numbers
The store module provides a clean interface that could easily be replaced with a database backend in a production environment.
The API comes with 10 pre-loaded users for testing. You can immediately test GET requests without needing to create data first.
This project maintains high code quality standards:
- Pylint Score: 10.00/10 across all modules
- Documentation: Comprehensive docstrings for all classes, methods, and functions
- Type Hints: Full type annotation coverage for better IDE support and code clarity
- Testing: 100% test coverage for serializers and API endpoints
- Standards: Follows PEP 8 and Django best practices
- No Database: Uses in-memory storage for demo simplicity
- Environment: Configured for development with Django's debug mode
- Validation: All inputs are validated using Django REST Framework serializers
- Error Handling: Proper HTTP status codes and error responses using DRF
- Testing: Modern pytest setup with Django integration and comprehensive test coverage
- Code Style: Follows Python and Django best practices with perfect linting scores
- Architecture: Uses Django's app-based architecture with clear separation of concerns
- Documentation: Every module, class, and function includes detailed docstrings