Skip to content

ShamsRupak/pulseapi

Repository files navigation

PulseAPI

Production-grade Team Task & Incident Tracker REST API

PulseAPI is a production-grade backend service designed to demonstrate real-world software engineering practices, including clean architecture, authentication, caching, observability, testing, and CI/CD. Built with FastAPI, PostgreSQL, Redis, and Docker, it showcases scalable API design, reliability-focused patterns, and developer-friendly tooling.

This project emphasizes production concerns such as maintainability, performance tradeoffs, and developer experience.

Python FastAPI PostgreSQL Redis License


Architecture Overview

┌──────────────────────────────────────────────────────────────┐
│                        Client / cURL                         │
└──────────────┬───────────────────────────────────────────────┘
               │
┌──────────────▼───────────────────────────────────────────────┐
│  FastAPI Application                                         │
│  ┌─────────────┐  ┌──────────────┐  ┌────────────────────┐   │
│  │  Middleware │  │  Exception   │  │   OpenAPI / Docs   │   │
│  │ RequestID   │  │  Handlers    │  │   /docs  /redoc    │   │
│  │ Metrics     │  └──────────────┘  └────────────────────┘   │
│  │ CORS        │                                             │
│  └──────┬──────┘                                             │
│         │                                                    │
│  ┌──────▼──────────────────────────────────────────────────┐ │
│  │  API Layer (routes)  /api/v1/...                        │ │
│  │  auth │ projects │ tasks │ incidents │ admin │ health   │ │
│  └──────┬──────────────────────────────────────────────────┘ │
│         │                                                    │
│  ┌──────▼──────────────────────────────────────────────────┐ │
│  │  Service Layer (business logic)                         │ │
│  │  AuthService │ ProjectService │ TaskService │ ...       │ │
│  └──────┬──────────────────────────────────────────────────┘ │
│         │                                                    │
│  ┌──────▼──────────────────────────────────────────────────┐ │
│  │  Repository Layer (data access)                         │ │
│  │  BaseRepository → UserRepo │ ProjectRepo │ TaskRepo     │ │
│  └──────┬──────────────────────────────────────────────────┘ │
│         │                                                    │
└─────────┼────────────────────────────────────────────────────┘
          │
    ┌─────▼─────┐     ┌───────────┐
    │ PostgreSQL│     │   Redis   │
    │  (data)   │     │ (cache +  │
    │           │     │  rate     │
    │           │     │  limit)   │
    └───────────┘     └───────────┘

Tech Stack

Component Technology
Language Python 3.11+
Framework FastAPI
Database PostgreSQL 16 + SQLAlchemy 2.x
Migrations Alembic
Caching Redis 7
Auth JWT (access + refresh tokens)
Validation Pydantic v2
Testing Pytest + pytest-asyncio
Linting Ruff + Black
CI GitHub Actions
Containerization Docker + docker-compose

Features

Authentication & Security

  • Email + password registration and login
  • Password hashing with bcrypt
  • JWT access token + refresh token flow
  • Role-based access control (user, admin)
  • CORS configuration, input validation everywhere

API Design

  • RESTful endpoints with pagination, filtering, sorting
  • Versioned API paths (/api/v1/...)
  • OpenAPI/Swagger docs at /docs
  • Standardized error responses with error codes

Data Modeling

  • Users, Projects, Tasks, Incidents, Comments, Audit Logs
  • SQLAlchemy models with relationships and indexes
  • Soft delete support on key tables
  • Audit log tracking all create/update/delete actions

Reliability & Observability

  • Structured JSON logging with request correlation IDs
  • /health endpoint (checks DB + Redis)
  • /metrics endpoint (request counts, error rates, latency)
  • Centralized exception handling

Caching & Rate Limiting

  • Redis-backed cache for GET list endpoints (30s TTL)
  • Cache invalidation on mutations
  • Fixed-window rate limiting per IP (general + strict for auth)

Developer Experience

  • Docker-based local development
  • Makefile for common commands
  • Comprehensive test suite (unit + integration)
  • GitHub Actions CI pipeline

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Python 3.11+ (for local development without Docker)

Setup

# Clone the repository
git clone https://github.com/ShamsRupak/pulseapi.git
cd pulseapi

# Copy environment variables
cp .env.example .env

# Start all services (app + postgres + redis)
make up

# The API is now running at http://localhost:8000
# Swagger docs: http://localhost:8000/docs

Local Development (without Docker)

# Create virtual environment
python -m venv .venv
source .venv/bin/activate

# Install dependencies
make setup

# Start postgres and redis (via Docker)
docker compose up -d postgres redis

# Run migrations
make migrate

# Start the server
uvicorn app.main:app --reload

Running Tests

# Run all tests
make test

# Run with coverage
make test-cov

# Run linting
make lint

# Auto-format code
make fmt

API Endpoints

Authentication

Method Endpoint Description
POST /api/v1/auth/register Register new user
POST /api/v1/auth/login Login, get tokens
POST /api/v1/auth/refresh Refresh access token
POST /api/v1/auth/logout Logout
GET /api/v1/auth/me Get current user

Projects

Method Endpoint Description
GET /api/v1/projects List projects
POST /api/v1/projects Create project
GET /api/v1/projects/{id} Get project
PATCH /api/v1/projects/{id} Update project
DELETE /api/v1/projects/{id} Delete project

Tasks

Method Endpoint Description
GET /api/v1/tasks List tasks (filter)
POST /api/v1/tasks Create task
GET /api/v1/tasks/{id} Get task
PATCH /api/v1/tasks/{id} Update task
DELETE /api/v1/tasks/{id} Delete task
GET /api/v1/tasks/{id}/comments List task comments
POST /api/v1/tasks/{id}/comments Add task comment

Incidents

Method Endpoint Description
GET /api/v1/incidents List incidents
POST /api/v1/incidents Report incident
GET /api/v1/incidents/{id} Get incident
PATCH /api/v1/incidents/{id} Update incident
DELETE /api/v1/incidents/{id} Delete incident
GET /api/v1/incidents/{id}/comments List incident comments
POST /api/v1/incidents/{id}/comments Add incident comment

Admin

Method Endpoint Description
GET /api/v1/admin/users List all users
POST /api/v1/admin/users/{id}/deactivate Deactivate user
GET /api/v1/admin/audit-logs View audit logs

System

Method Endpoint Description
GET /health Health check (DB + Redis)
GET /metrics Application metrics

Example cURL Commands

# Register a user
curl -X POST http://localhost:8000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"securepass123","full_name":"John Doe"}'

# Login
curl -X POST http://localhost:8000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"securepass123"}'

# Create a project (use the access_token from login)
curl -X POST http://localhost:8000/api/v1/projects \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -d '{"name":"My Project","slug":"my-project","description":"A sample project"}'

# Create a task
curl -X POST http://localhost:8000/api/v1/tasks \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -d '{"title":"Fix login bug","project_id":"<PROJECT_ID>","priority":"high"}'

# Report an incident
curl -X POST http://localhost:8000/api/v1/incidents \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -d '{"title":"DB Connection Timeout","severity":"SEV2","project_id":"<PROJECT_ID>"}'

# Health check
curl http://localhost:8000/health

Design Decisions

  1. Clean Architecture (Routes → Services → Repositories): Separates concerns clearly. Routes handle HTTP, services handle business logic, repositories handle data access. Makes testing and refactoring straightforward.

  2. Async-first with SQLAlchemy 2.x: Uses asyncpg for non-blocking database operations, matching FastAPI's async nature for better throughput under load.

  3. SQLite for Tests: Tests use in-memory SQLite via aiosqlite instead of requiring a running Postgres instance. This makes tests fast, isolated, and CI-friendly.

  4. Redis Fail-Open Strategy: If Redis is unavailable, rate limiting and caching degrade gracefully rather than blocking requests. The application remains functional.

  5. Soft Deletes: Key entities use deleted_at timestamps instead of hard deletes, preserving data for audit trails and potential recovery.

  6. Fixed-Window Rate Limiting: Simple and effective. Separate limits for auth endpoints (stricter) vs general endpoints.

  7. UUID Primary Keys: Avoids sequential ID enumeration attacks and works well in distributed systems.

Project Structure

pulseapi/
├── app/
│   ├── main.py                 # FastAPI application entry point
│   ├── api/v1/routes/          # API route handlers
│   ├── core/                   # Config, security, logging, middleware
│   ├── db/                     # Database session, base, migrations
│   ├── models/                 # SQLAlchemy models
│   ├── schemas/                # Pydantic request/response schemas
│   ├── services/               # Business logic layer
│   ├── repositories/           # Data access layer
│   └── utils/                  # Shared utilities
├── tests/
│   ├── unit/                   # Unit tests
│   └── integration/            # Integration tests
├── docs/                       # Additional documentation
├── docker-compose.yml          # Local dev environment
├── Dockerfile                  # Container image
├── Makefile                    # Common commands
├── pyproject.toml              # Python project config
└── alembic.ini                 # Migration config

Roadmap

  • WebSocket support for real-time incident updates
  • Email notifications for incident severity changes
  • Prometheus metrics exporter
  • API key authentication for service-to-service calls
  • Incident timeline as a first-class entity (separate table)
  • File attachments for tasks and incidents
  • OpenTelemetry tracing integration

License

MIT

About

FastAPI backend with JWT authentication, PostgreSQL, Redis caching, and rate limiting.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages