Skip to content

Professional FastAPI REST API with JWT authentication, SQLAlchemy ORM, role-based access control, and comprehensive CRUD operations. Features user management, admin dashboard, automated testing, and production-ready deployment configuration.

License

Notifications You must be signed in to change notification settings

FCHEHIDI/APIs-Development-with-FastAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Professional FastAPI Application

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

🎯 Project Overview

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.

⭐ Key Features

πŸ” Authentication & Security

  • 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

πŸ“Š Database & ORM

  • SQLAlchemy ORM with relationship mapping
  • Database Migrations support (ready for Alembic)
  • Connection Pooling and transaction management
  • Support for PostgreSQL and SQLite

πŸ› οΈ API Features

  • 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

πŸ—οΈ Architecture & Code Quality

  • 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

πŸ“ Project Structure

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

πŸš€ Quick Start

Prerequisites

  • Python 3.10 or higher
  • pip or poetry for package management

Installation

  1. Clone the repository

    git clone https://github.com/FCHEHIDI/APIs-Development-with-FastAPI.git
    cd APIs-Development-with-FastAPI
  2. Create and activate virtual environment

    python -m venv .venv
    # On Windows
    .venv\Scripts\activate
    # On macOS/Linux
    source .venv/bin/activate
  3. Install dependencies

    pip install -r requirements.txt
  4. Set up environment variables

    cp .env.example .env
    # Edit .env with your configuration
  5. Run the application

    cd app
    python main.py

    Or using uvicorn directly:

    uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
  6. Access the application

πŸ“– API Documentation

Authentication Endpoints

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

User Management Endpoints

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

Post Management Endpoints

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)

πŸ§ͺ Testing

Run All Tests

pytest

Run with Coverage

pytest --cov=app --cov-report=html

Run Specific Test Categories

# Unit tests only
pytest tests/unit/

# Integration tests only
pytest tests/integration/

# Specific test file
pytest tests/unit/test_auth.py -v

πŸ“Š API Usage Examples

Register a New User

curl -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"
     }'

Login and Get Token

curl -X POST "http://localhost:8000/api/v1/auth/login/json" \
     -H "Content-Type: application/json" \
     -d '{
       "username": "newuser",
       "password": "securepassword123"
     }'

Create a Post

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
     }'

πŸ”§ Configuration

Environment Variables

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 *

Database Configuration

SQLite (Default)

DATABASE_URL=sqlite:///./app.db

PostgreSQL

DATABASE_URL=postgresql://username:password@localhost:5432/dbname

🐳 Docker Deployment (Optional)

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-app

πŸ“ˆ Performance & Monitoring

Health Check

The application includes a health check endpoint at /health for monitoring purposes.

Structured Logging

All operations are logged with structured data for easy monitoring and debugging.

Request Timing

Response times are automatically tracked and included in response headers.

πŸ”’ Security Features

  • 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

πŸ§‘β€πŸ’» Developer Experience

Code Quality Tools

# Format code with Black
black app/ tests/

# Lint code with Flake8
flake8 app/ tests/

# Type checking with MyPy
mypy app/

Database Migrations (Future Enhancement)

Set up Alembic for database migrations:

alembic init migrations
alembic revision --autogenerate -m "Initial migration"
alembic upgrade head

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

🎯 Skills Demonstrated

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

πŸ“ž Contact

For questions or collaboration opportunities, please reach out:


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.

About

Professional FastAPI REST API with JWT authentication, SQLAlchemy ORM, role-based access control, and comprehensive CRUD operations. Features user management, admin dashboard, automated testing, and production-ready deployment configuration.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages