A comprehensive, production-ready REST API built with FastAPI, demonstrating best practices for modern backend development. This project showcases advanced FastAPI features, clean architecture, and professional development practices suitable for enterprise applications.
Built by: Fares Chehidi
Email: fareschehidi7@gmail.com
LinkedIn: https://www.linkedin.com/in/fares-chehidi
GitHub: https://github.com/FCHEHIDI
This FastAPI application serves as a complete backend solution for user management and content publishing, featuring JWT authentication, CRUD operations, and comprehensive security measures. It's designed to demonstrate proficiency in backend development for potential employers and serves as a template for production applications.
- JWT Token Authentication with automatic expiration
- Password Hashing using bcrypt
- Role-based Access Control (User/Superuser)
- Security Headers and CORS configuration
- Input Validation and sanitization
- SQLAlchemy ORM with relationship mapping
- Database Migrations support (ready for Alembic)
- Connection Pooling and transaction management
- Support for PostgreSQL and SQLite
- RESTful API Design following OpenAPI standards
- Automatic API Documentation (Swagger/ReDoc)
- Request/Response Validation with Pydantic
- Error Handling with custom exception handlers
- Structured Logging for monitoring and debugging
- Clean Architecture with separation of concerns
- Service Layer Pattern for business logic
- Dependency Injection with FastAPI's DI system
- Type Hints throughout the codebase
- Comprehensive Testing with pytest
fastapi_project/
β
βββ app/ # Main application package
β βββ main.py # FastAPI app instance and configuration
β βββ api/ # API route handlers
β β βββ routes/ # Individual route modules
β β β βββ auth.py # Authentication endpoints
β β β βββ users.py # User management endpoints
β β β βββ posts.py # Post management endpoints
β β βββ dependencies/ # Shared dependencies
β β βββ auth.py # Authentication dependencies
β βββ core/ # Core application components
β β βββ config.py # Application configuration
β β βββ security.py # Security utilities
β β βββ database.py # Database configuration
β βββ models/ # SQLAlchemy models
β β βββ __init__.py # Database models (User, Post)
β βββ schemas/ # Pydantic schemas
β β βββ __init__.py # Request/response models
β βββ services/ # Business logic layer
β β βββ user_service.py # User operations
β β βββ post_service.py # Post operations
β βββ utils/ # Utility functions
β βββ helpers.py # Helper functions and logging
β
βββ tests/ # Test suite
β βββ conftest.py # Test configuration and fixtures
β βββ unit/ # Unit tests
β β βββ test_auth.py # Authentication tests
β βββ integration/ # Integration tests
β βββ test_workflows.py # End-to-end workflow tests
β
βββ requirements.txt # Project dependencies
βββ .env.example # Environment variables template
βββ .env # Environment configuration (local)
βββ README.md # This file
- Python 3.10 or higher
- pip or poetry for package management
-
Clone the repository
git clone https://github.com/FCHEHIDI/APIs-Development-with-FastAPI.git cd APIs-Development-with-FastAPI -
Create and activate virtual environment
python -m venv .venv # On Windows .venv\Scripts\activate # On macOS/Linux source .venv/bin/activate
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Run the application
cd app python main.pyOr using uvicorn directly:
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
-
Access the application
- API Documentation: http://localhost:8000/docs
- Alternative Docs: http://localhost:8000/redoc
- Health Check: http://localhost:8000/health
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| POST | /api/v1/auth/register |
Register new user | None |
| POST | /api/v1/auth/login |
Login (form data) | None |
| POST | /api/v1/auth/login/json |
Login (JSON) | None |
| GET | /api/v1/auth/me |
Get current user | Bearer Token |
| POST | /api/v1/auth/logout |
Logout | Bearer Token |
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| GET | /api/v1/users/ |
List all users | Superuser |
| GET | /api/v1/users/me |
Get current user | Bearer Token |
| GET | /api/v1/users/{user_id} |
Get user by ID | Superuser |
| PUT | /api/v1/users/me |
Update current user | Bearer Token |
| PUT | /api/v1/users/{user_id} |
Update user by ID | Superuser |
| DELETE | /api/v1/users/{user_id} |
Delete user | Superuser |
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| GET | /api/v1/posts/ |
List posts | Optional |
| GET | /api/v1/posts/my-posts |
Get user's posts | Bearer Token |
| GET | /api/v1/posts/{post_id} |
Get post by ID | Optional |
| POST | /api/v1/posts/ |
Create post | Bearer Token |
| PUT | /api/v1/posts/{post_id} |
Update post | Bearer Token (Owner) |
| DELETE | /api/v1/posts/{post_id} |
Delete post | Bearer Token (Owner) |
pytestpytest --cov=app --cov-report=html# Unit tests only
pytest tests/unit/
# Integration tests only
pytest tests/integration/
# Specific test file
pytest tests/unit/test_auth.py -vcurl -X POST "http://localhost:8000/api/v1/auth/register" \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"username": "newuser",
"full_name": "New User",
"password": "securepassword123"
}'curl -X POST "http://localhost:8000/api/v1/auth/login/json" \
-H "Content-Type: application/json" \
-d '{
"username": "newuser",
"password": "securepassword123"
}'curl -X POST "http://localhost:8000/api/v1/posts/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{
"title": "My First Post",
"content": "This is the content of my first post.",
"is_published": true
}'| Variable | Description | Default |
|---|---|---|
DEBUG |
Enable debug mode | False |
HOST |
Server host | 0.0.0.0 |
PORT |
Server port | 8000 |
DATABASE_URL |
Database connection string | sqlite:///./app.db |
SECRET_KEY |
JWT secret key | Required |
ACCESS_TOKEN_EXPIRE_MINUTES |
Token expiration time | 30 |
CORS_ORIGINS |
Allowed CORS origins | * |
SQLite (Default)
DATABASE_URL=sqlite:///./app.db
PostgreSQL
DATABASE_URL=postgresql://username:password@localhost:5432/dbname
Create a Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY app/ ./app/
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Build and run:
docker build -t fastapi-app .
docker run -p 8000:8000 fastapi-appThe application includes a health check endpoint at /health for monitoring purposes.
All operations are logged with structured data for easy monitoring and debugging.
Response times are automatically tracked and included in response headers.
- Password Hashing: Uses bcrypt with salt
- JWT Tokens: Secure token-based authentication
- CORS Protection: Configurable CORS policies
- Input Validation: Automatic request validation
- SQL Injection Protection: Using SQLAlchemy ORM
- Rate Limiting: Ready for implementation
# Format code with Black
black app/ tests/
# Lint code with Flake8
flake8 app/ tests/
# Type checking with MyPy
mypy app/Set up Alembic for database migrations:
alembic init migrations
alembic revision --autogenerate -m "Initial migration"
alembic upgrade head- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
This project demonstrates proficiency in:
- FastAPI Framework: Advanced usage of FastAPI features
- Database Design: SQLAlchemy ORM with relationships
- Authentication: JWT implementation and security
- API Design: RESTful API principles and documentation
- Testing: Comprehensive unit and integration testing
- Code Architecture: Clean code and separation of concerns
- Documentation: Clear and comprehensive documentation
- Security: Implementation of security best practices
- Error Handling: Robust error handling and validation
For questions or collaboration opportunities, please reach out:
- Portfolio: GitHub Profile
- LinkedIn: Fares Chehidi
- Email: fareschehidi7@gmail.com
This project serves as a demonstration of professional backend development skills using FastAPI. Built by Fares Chehidi to showcase expertise in modern Python web development, API design, and backend engineering practices.