Skip to content

About

Production-style Employee Management REST API built with FastAPI, SQLModel, Pydantic, authentication, CRUD, search, filtering, pagination, and Docker.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ‘¨β€πŸ’Ό Employee Management REST API

A production-style Employee Management REST API built with FastAPI, SQLModel, Pydantic, dependency injection, CRUD operations, search, filtering, sorting, pagination, Argon2 password hashing, logging, OpenAPI/Swagger, and Docker.

Python FastAPI SQLModel SQLite Docker OpenAPI


πŸ“Œ Table of Contents

Click to expand

πŸ“– Project Overview

This project implements a production-style Employee Management REST API using FastAPI and SQLModel.

The API demonstrates common backend engineering patterns including:

  • RESTful CRUD operations
  • Request and response validation with Pydantic
  • SQLModel-based database access
  • FastAPI dependency injection
  • Search, filtering, sorting, and pagination
  • Authentication with Argon2 password hashing
  • Centralized exception handling
  • Application logging
  • Automatic OpenAPI/Swagger documentation
  • Docker containerization

The project is structured into separate modules for routes, schemas, models, database access, and security so that each responsibility remains easy to understand and maintain.


✨ Features

πŸ‘¨β€πŸ’Ό Employee Management

  • Create employee
  • Get all employees
  • Get employee by ID
  • Update employee with PUT
  • Partially update employee with PATCH
  • Delete employee

πŸ”Ž Querying

  • Search by employee name or email
  • Filter by department
  • Filter by active/inactive status
  • Sort by name or salary
  • Ascending/descending order
  • Offset/limit pagination
  • Combine multiple query parameters

πŸ›‘οΈ API Quality

  • Pydantic request validation
  • Response models
  • HTTP status codes
  • 404 handling for missing employees
  • 409 handling for duplicate users
  • 401 handling for invalid login
  • Database exception handling
  • Logging

πŸ” Authentication

  • User registration
  • Password hashing using Argon2
  • Password verification during login

🐳 Deployment

  • Dockerfile included
  • Docker image build
  • Containerized Uvicorn server

πŸ—οΈ System Architecture

flowchart TD
    C[🌐 Client / Browser / Postman / Swagger]

    subgraph APP[FastAPI Application]
        M[main.py]
        AR[πŸ” Auth Router]
        ER[πŸ‘¨β€πŸ’Ό Employee Router]
        S[πŸ›‘οΈ Pydantic Schemas]
        D[πŸ’‰ get_session Dependency]
        SEC[πŸ”‘ Argon2 Security]
    end

    subgraph DATA[Persistence]
        ORM[SQLModel]
        DB[(SQLite employee.db)]
    end

    C -->|HTTP Request| M
    M --> AR
    M --> ER
    AR --> S
    ER --> S
    AR --> SEC
    AR --> D
    ER --> D
    D --> ORM
    ORM --> DB
    SEC --> DB
Loading

Architecture Flow

Client
  ↓
FastAPI Application
  ↓
APIRouter
  ↓
Pydantic Validation
  ↓
Dependency Injection
  ↓
SQLModel
  ↓
SQLite
  ↓
JSON Response

πŸ”„ Request Lifecycle

sequenceDiagram
    autonumber
    actor Client
    participant FastAPI
    participant Router as APIRouter
    participant Validator as Pydantic
    participant DI as Depends(get_session)
    participant DB as SQLite

    Client->>FastAPI: HTTP Request
    FastAPI->>Router: Route request
    Router->>Validator: Validate input

    alt Invalid input
        Validator-->>Client: 422 Validation Error
    else Valid input
        Validator->>DI: Request DB session
        DI->>DB: Open/Yield session
        Router->>DB: Execute query
        DB-->>Router: Result
        Router-->>FastAPI: Response model
        FastAPI-->>Client: JSON response
    end
Loading

πŸ“‚ Project Structure

employee-mgt-REST_API/
β”‚
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ main.py
β”‚   β”œβ”€β”€ database.py
β”‚   β”‚
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ employee_model.py
β”‚   β”‚   └── user_model.py
β”‚   β”‚
β”‚   β”œβ”€β”€ schemas/
β”‚   β”‚   β”œβ”€β”€ auth.py
β”‚   β”‚   └── employee_schema.py
β”‚   β”‚
β”‚   β”œβ”€β”€ routers/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ employees.py
β”‚   β”‚   └── auth.py
β”‚   β”‚
β”‚   └── security/
β”‚       β”œβ”€β”€ __init__.py
β”‚       └── security.py
β”‚
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .env.example
β”œβ”€β”€ .gitignore
β”œβ”€β”€ README.md
└── employee.db              # Runtime-generated; should be gitignored

Responsibility of Each Layer

Layer Responsibility
main.py Creates FastAPI application and mounts routers
database.py Database engine and session dependency
models/ SQLModel database entities
schemas/ Request and response validation
routers/ API endpoints and route logic
security/ Password hashing and verification
Dockerfile Container image configuration

πŸ› οΈ Tech Stack

Component Technology Purpose
Language Python 3.13+ Application development
Framework FastAPI REST API framework
ORM / Models SQLModel Database models and queries
Validation Pydantic v2 Request/response validation
Database SQLite Local persistence
Password Hashing pwdlib[argon2] Secure password hashing
Server Uvicorn ASGI application server
Containerization Docker Reproducible deployment
Version Control Git + GitHub Source control and project hosting
API Documentation OpenAPI / Swagger / ReDoc Interactive API documentation

πŸš€ Setup & Installation

1. Clone the Repository

git clone <YOUR_GITHUB_REPOSITORY_URL>
cd employee-mgt-REST_API

2. Create Virtual Environment

macOS / Linux

python3.13 -m venv venv
source venv/bin/activate

Windows

python -m venv venv
venv\Scripts\activate

3. Install Dependencies

pip install --upgrade pip
pip install -r requirements.txt

Important: pwdlib[argon2] is required because the project uses Argon2 password hashing.

4. Configure Environment

cp .env.example .env

Example:

DATABASE_URL=sqlite:///employee.db

5. Start the API

uvicorn app.main:app --reload --host 127.0.0.1 --port 8000

API:

http://127.0.0.1:8000

πŸ“š Interactive API Documentation

FastAPI automatically generates OpenAPI documentation.

Documentation URL
Swagger UI http://127.0.0.1:8000/docs
ReDoc http://127.0.0.1:8000/redoc
OpenAPI JSON http://127.0.0.1:8000/openapi.json

Swagger can be used to send requests directly to the running API.


πŸ“‘ API Endpoints

πŸ‘¨β€πŸ’Ό Employee CRUD

Base path:

/employee/employees
Method Endpoint Purpose
GET /employee/employees/check Health/status check
POST /employee/employees/ Create employee
GET /employee/employees/ List employees
GET /employee/employees/{id} Get employee
PUT /employee/employees/{id} Full update
PATCH /employee/employees/{id} Partial update
DELETE /employee/employees/{id} Delete employee

Create Employee

POST /employee/employees/
{
  "name": "Vijay Sharma",
  "email": "[email protected]",
  "department": "Engineering",
  "salary": 85000,
  "is_active": true
}

Partial Update

PATCH /employee/employees/1
{
  "salary": 92000
}

πŸ” Search, Filtering, Sorting & Pagination

The list endpoint supports multiple query parameters.

GET /employee/employees/

Search

GET /employee/employees/?search=Vijay

Search can match employee name or email.

Department Filter

GET /employee/employees/?department=IT

Active Status Filter

GET /employee/employees/?is_active=true

Sort by Salary

GET /employee/employees/?sort_by=salary&order=desc

Pagination

GET /employee/employees/?offset=0&limit=10
GET /employee/employees/?offset=10&limit=10

The configured limit is capped at a maximum of 50 records per request.

Combined Query

GET /employee/employees/?department=IT&is_active=true&sort_by=salary&order=desc&limit=5&offset=0

Query Flow

flowchart LR
    A[Employees] --> B[Search]
    B --> C[Department Filter]
    C --> D[Status Filter]
    D --> E[Sort]
    E --> F[Pagination]
    F --> G[JSON Response]
Loading

πŸ” Authentication

The authentication subsystem provides user registration and login.

Current implementation note: The existing code currently exposes the authentication routes with the /auth/... path because the /auth prefix is applied at both router and application inclusion levels. The README documents the current behavior rather than hiding it.

Method Current Route Purpose
POST /auth/register Register user
POST /auth/login Authenticate user

Registration

{
  "username": "vijay",
  "password": "StrongPassword@123"
}

Authentication Concepts

Authentication
    ↓
"Who are you?"
    ↓
Username + Password
    ↓
Password Verification

This project demonstrates authentication. It does not currently implement a complete role-based authorization system such as admin/user permissions.


πŸ›‘οΈ Validation & Error Handling

Pydantic validates incoming request data before it reaches the database layer.

Validation

Invalid input can result in:

422 Unprocessable Entity

For example, an invalid email format is rejected by the request schema.

Employee Not Found

A missing employee returns:

404 Not Found

Example:

{
  "detail": "999 not found in the records"
}

Duplicate User

Attempting to register an existing username returns:

409 Conflict

Invalid Login

Incorrect credentials return:

401 Unauthorized

Database Errors

Database-related exceptions are handled by the application and logged rather than exposing internal implementation details directly to the client.


πŸ’‰ Dependency Injection

The project uses FastAPI dependency injection to provide database sessions to route handlers.

Example:

@router.get("/", response_model=list[EmployeeRead])
def get_employees(
    session: Session = Depends(get_session),
    search: str | None = None
):
    ...

Why Dependency Injection?

  • Keeps database session creation outside route logic
  • Provides a clean session lifecycle
  • Reduces duplicated database setup code
  • Makes route logic easier to test and maintain

πŸ” Password Security

Passwords are not stored as plaintext.

The project uses:

pwdlib[argon2]

Registration Flow

flowchart TD
    P[Plain Password] --> H[Argon2 Hasher]
    H --> DB[(Hashed Password)]
Loading

Login Flow

flowchart TD
    P[Submitted Password] --> V[Argon2 Verification]
    DB[(Stored Hash)] --> V
    V -->|Valid| OK[Authenticated]
    V -->|Invalid| ERR[401 Unauthorized]
Loading

The purpose is to store a password hash rather than the original password.


🐳 Docker

The API can be packaged and run as a Docker container.

Build Image

docker build -t employee-management-api .

Run Container

docker run --name employee-api -p 8000:8080 employee-management-api

This maps:

Host:      8000
    ↓
Docker:    8080

The API is then accessible at:

http://127.0.0.1:8000

Check Container

docker ps

View Logs

docker logs employee-api

Stop Container

docker stop employee-api

Remove Container

docker rm employee-api

πŸ§ͺ Testing Checklist

The following areas were tested during project development.

CRUD

  • Create employee
  • Get employee list
  • Get employee by ID
  • Update employee with PUT
  • Partial update with PATCH
  • Delete employee
  • 404 for non-existent employee

Search / Filter / Sort / Pagination

  • Search by name
  • Search by email
  • Filter by department
  • Filter by active status
  • Sort by salary
  • Pagination with offset/limit
  • Combined query parameters

Authentication

  • Register user
  • Reject duplicate username
  • Login with valid password
  • Reject incorrect password
  • Password stored as Argon2 hash

Docker

  • Docker image builds
  • Container starts successfully
  • Uvicorn runs inside container
  • Swagger is accessible through mapped host port

Documentation

  • Swagger UI
  • ReDoc
  • OpenAPI schema

πŸŽ₯ Project Walkthrough

For the project video, demonstrate the project in this order:

1. Introduction

Explain:

  • What problem the API solves
  • Why FastAPI was selected
  • Project folder structure

2. Architecture

Show:

Client
  ↓
FastAPI
  ↓
APIRouter
  ↓
Pydantic
  ↓
Dependency Injection
  ↓
SQLModel
  ↓
SQLite

3. Swagger Demo

Open:

http://127.0.0.1:8000/docs

Demonstrate:

  1. Create employee
  2. Get employees
  3. Get employee by ID
  4. Update employee
  5. Patch employee
  6. Delete employee
  7. Search
  8. Filter
  9. Sort
  10. Pagination

4. Authentication

Demonstrate:

  1. Register user
  2. Attempt duplicate registration
  3. Login with wrong password
  4. Login with correct password
  5. Explain Argon2 hashing

5. Docker

Show:

docker build -t employee-management-api .
docker run --name employee-api -p 8000:8080 employee-management-api

Then open Swagger through port 8000.


🌿 Git & GitHub Workflow

Recommended workflow:

flowchart LR
    A[Code Changes] --> B[git status]
    B --> C[git add .]
    C --> D[git diff --cached]
    D --> E[git commit]
    E --> F[git push origin main]
    F --> G[GitHub]
Loading

Check Changes

git status

Stage Changes

git add .

Review Staged Changes

git diff --cached

Commit

git commit -m "Complete employee management REST API"

Push

git push origin main

Important Files to Keep Out of Git

Your .gitignore should exclude:

venv/
.venv/
.env
__pycache__/
*.pyc
*.db

Never commit real passwords, API keys, or other secrets.


πŸ“Œ Learning Outcomes

This project demonstrates practical understanding of:

  • REST API design
  • FastAPI routing
  • APIRouter
  • Pydantic validation
  • Response models
  • SQLModel
  • SQLite
  • Dependency injection
  • CRUD operations
  • Search and filtering
  • Sorting
  • Pagination
  • Exception handling
  • Logging
  • Password hashing with Argon2
  • Swagger / OpenAPI
  • Docker containerization
  • Git and GitHub workflow

πŸ‘¨β€πŸ’» Author

Vijay Rangvani

Backend & AI Engineering Learner


Built with FastAPI, SQLModel, Python 3.13, SQLite, and Docker.

About

Production-style Employee Management REST API built with FastAPI, SQLModel, Pydantic, authentication, CRUD, search, filtering, pagination, and Docker.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages