Skip to content

Inklikdevteam/Leave-management-system

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI Backend Scaffold

A comprehensive FastAPI backend scaffold with SQLAlchemy, Alembic, Pydantic, authentication, and email capabilities.

Features

  • FastAPI: Modern, fast web framework for building APIs
  • SQLAlchemy: Powerful ORM for database operations
  • Alembic: Database migration tool
  • Pydantic: Data validation using Python type annotations
  • Authentication: JWT-based authentication with password hashing
  • Email Support: SMTP email configuration
  • Structured Logging: Centralized logging setup
  • Error Handling: Custom exception classes
  • Repository Pattern: Clean architecture with separation of concerns
  • Service Layer: Business logic abstraction
  • Environment Management: Pydantic settings with .env support

Project Structure

.
├── app/
│   ├── __init__.py
│   ├── api/
│   │   ├── __init__.py
│   │   ├── deps.py          # Dependencies (authentication, etc.)
│   │   └── v1/
│   │       ├── __init__.py
│   │       ├── api.py        # API router aggregation
│   │       ├── auth.py       # Authentication endpoints
│   │       └── health.py     # Health check endpoint
│   ├── core/
│   │   ├── __init__.py
│   │   ├── config.py         # Pydantic settings
│   │   ├── database.py       # Database configuration
│   │   ├── security.py       # Security utilities
│   │   ├── logging.py        # Logging configuration
│   │   └── exceptions.py     # Custom exceptions
│   ├── models/
│   │   ├── __init__.py
│   │   └── user.py           # SQLAlchemy models
│   ├── repositories/
│   │   ├── __init__.py
│   │   ├── base.py           # Base CRUD operations
│   │   └── user.py           # User repository
│   ├── services/
│   │   ├── __init__.py
│   │   └── user.py           # User business logic
│   └── main.py               # FastAPI application entry point
├── alembic/
│   ├── versions/             # Migration files
│   ├── env.py                # Alembic environment configuration
│   ├── script.py.mako        # Migration script template
├── logs/                     # Application logs (created automatically)
├── .env.example              # Environment variables template
├── .gitignore
├── alembic.ini               # Alembic configuration
├── pyproject.toml            # Poetry dependencies and configuration
└── README.md

Setup Instructions

Prerequisites

  • Python 3.11+
  • PostgreSQL (or modify DATABASE_URL for your preferred database)
  • Poetry (recommended) or pip

Installation

  1. Clone the repository:

    git clone <repository-url>
    cd fastapi-backend
  2. Install dependencies:

    # Using Poetry (recommended)
    poetry install
    
    # Or using pip
    pip install -r requirements.txt  # If you generate requirements.txt
  3. Set up environment variables:

    cp .env.example .env
    # Edit .env with your configuration
  4. Configure the database:

    • Create a PostgreSQL database
    • Update DATABASE_URL in your .env file
  5. Run database migrations:

    # Using Poetry
    poetry run alembic upgrade head
    
    # Or using pip
    alembic upgrade head

Running the Application

Development

# Using Poetry
poetry run uvicorn app.main:app --reload

# Or using pip
uvicorn app.main:app --reload

The application will be available at http://localhost:8000

API Documentation

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • OpenAPI Schema: http://localhost:8000/api/v1/openapi.json

Available Endpoints

Health Check

  • GET /api/v1/health - Health check with database connectivity

Authentication

  • POST /api/v1/auth/login - Login and get access token

Root

  • GET / - Basic API information

Database Migrations

Create a new migration

# Using Poetry
poetry run alembic revision --autogenerate -m "Description of changes"

# Or using pip
alembic revision --autogenerate -m "Description of changes"

Apply migrations

# Using Poetry
poetry run alembic upgrade head

# Or using pip
alembic upgrade head

Rollback migrations

# Using Poetry
poetry run alembic downgrade -1

# Or using pip
alembic downgrade -1

Development Tools

Code Formatting

# Using Poetry
poetry run black .
poetry run isort .

# Or using pip
black .
isort .

Type Checking

# Using Poetry
poetry run mypy .

# Or using pip
mypy .

Linting

# Using Poetry
poetry run flake8 .

# Or using pip
flake8 .

Running Tests

# Using Poetry
poetry run pytest

# Or using pip
pytest

Environment Variables

Key environment variables (see .env.example for complete list):

  • DATABASE_URL: Database connection string
  • SECRET_KEY: JWT secret key (change in production!)
  • ALGORITHM: JWT algorithm (default: HS256)
  • ACCESS_TOKEN_EXPIRE_MINUTES: Token expiration time
  • SMTP_*: Email configuration settings
  • DEBUG: Enable debug mode
  • ENVIRONMENT: Application environment (development/staging/production)

Adding New Features

1. Create a Model

Add your SQLAlchemy model to app/models/:

# app/models/your_model.py
from sqlalchemy import Column, Integer, String
from app.core.database import Base

class YourModel(Base):
    __tablename__ = "your_models"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)

2. Create Repository

Add repository logic to app/repositories/:

# app/repositories/your_model.py
from app.models.your_model import YourModel
from app.repositories.base import CRUDBase

class CRUDYourModel(CRUDBase[YourModel, Any, Any]):
    pass

your_model = CRUDYourModel(YourModel)

3. Create Service

Add business logic to app/services/:

# app/services/your_model.py
from app.repositories.your_model import your_model

class YourModelService:
    def __init__(self):
        self.repo = your_model
    
    def create_your_model(self, db, *, name: str):
        return self.repo.create(db, obj_in={"name": name})

your_model_service = YourModelService()

4. Create API Endpoints

Add API routes to app/api/v1/:

# app/api/v1/your_model.py
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.services.your_model import your_model_service

router = APIRouter()

@router.post("/your-models")
def create_your_model(name: str, db: Session = Depends(get_db)):
    return your_model_service.create_your_model(db=db, name=name)

5. Register Routes

Add your router to app/api/v1/api.py:

from app.api.v1 import your_model

api_router.include_router(your_model.router, prefix="/your-models", tags=["your-model"])

6. Generate Migration

alembic revision --autogenerate -m "Add your model"
alembic upgrade head

Production Considerations

  1. Security:

    • Change SECRET_KEY in production
    • Use HTTPS in production
    • Set appropriate CORS origins
    • Enable environment-specific configurations
  2. Database:

    • Use connection pooling
    • Set appropriate database limits
    • Regular backups
  3. Logging:

    • Configure log rotation
    • Use structured logging for production
    • Set appropriate log levels
  4. Performance:

    • Add database indexes
    • Implement caching where needed
    • Monitor application performance

Contributing

  1. Follow the existing code style (Black + isort)
  2. Add tests for new features
  3. Update documentation
  4. Run type checking and linting before committing

License

Add your license information here.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •