Skip to content

SynthoraAI-AI-News-Content-Curator/API-Gateway-Service

Repository files navigation

SynthoraAI API Gateway

Production-Ready API Gateway for SynthoraAI Content Curator

License: MIT Node.js Version TypeScript Docker


Overview

The SynthoraAI API Gateway is a production-ready, enterprise-grade API gateway service that serves as the central entry point for the SynthoraAI AI-Powered Content Curator system. It provides intelligent routing, authentication, rate limiting, caching, circuit breaking, and comprehensive monitoring for all microservices in the ecosystem.

Purpose

This gateway helps government officials and authorized users access the latest news information and AI-generated summarizations by:

  • Centralized Access: Single point of entry for all SynthoraAI services
  • Security: JWT-based authentication and role-based authorization
  • Performance: Redis-backed caching and intelligent request routing
  • Resilience: Circuit breaker pattern for automatic failover
  • Observability: Real-time metrics and comprehensive logging

Features

🚀 Core Features

  • Microservices Routing: Intelligent request routing to Backend, Crawler, and Newsletter services
  • Authentication & Authorization: JWT-based auth with role-based access control
  • Rate Limiting: Configurable rate limits per endpoint to prevent abuse
  • Caching: Redis-backed caching for improved performance
  • Circuit Breaker: Automatic failover and recovery for downstream services
  • API Versioning: Support for multiple API versions (v1, v2, etc.)

📊 Monitoring & Observability

  • Real-time Metrics: Request counts, response times, error rates
  • Circuit Breaker Status: Monitor health of all downstream services
  • Structured Logging: Winston-based logging with multiple transports
  • Health Checks: Comprehensive health endpoints for all services

🔒 Security

  • Helmet.js: Security headers and XSS protection
  • CORS: Configurable cross-origin resource sharing
  • Input Validation: Request validation using express-validator
  • API Keys: Service-to-service authentication

🛠️ Developer Experience

  • TypeScript: Full type safety and excellent IDE support
  • Swagger/OpenAPI: Interactive API documentation
  • Docker Support: Production-ready containerization
  • CI/CD Ready: GitHub Actions workflows included
  • Comprehensive Tests: Unit and integration tests with Jest

Quick Start

Prerequisites

  • Node.js >= 18.0.0
  • npm >= 9.0.0
  • Redis >= 7.0 (for caching and rate limiting)
  • Docker (optional, for containerized deployment)

Installation

# Clone the repository
git clone https://github.com/SynthoraAI/API-Gateway-Service.git
cd API-Gateway-Service

# Install dependencies
npm install

# Copy environment variables
cp .env.example .env

# Edit .env with your configuration
nano .env

Configuration

Create a .env file in the root directory:

# Server Configuration
NODE_ENV=development
PORT=8080
HOST=0.0.0.0

# Service URLs
BACKEND_URL=https://ai-content-curator-backend.vercel.app
CRAWLER_URL=https://ai-content-curator-crawler.vercel.app
NEWSLETTER_URL=https://ai-content-curator-newsletters.vercel.app

# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRES_IN=24h

# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# CORS
ALLOWED_ORIGINS=http://localhost:3000,https://synthoraai.vercel.app

Running Locally

# Development mode with hot reload
npm run dev

# Production build
npm run build
npm start

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Lint code
npm run lint

# Format code
npm run format

The gateway will be available at:

Using Docker

# Build and run with Docker Compose
docker-compose up -d

# Build Docker image only
docker build -t synthoraai-gateway .

# Run container
docker run -p 8080:8080 --env-file .env synthoraai-gateway

# View logs
docker-compose logs -f gateway

# Stop services
docker-compose down

Architecture

The API Gateway follows a modern microservices architecture with the following components:

┌─────────────────┐
│   Clients       │
│ (Frontend/Apps) │
└────────┬────────┘
         │
         ▼
┌─────────────────────────────────────────┐
│         API Gateway (Port 8080)         │
│  ┌───────────────────────────────────┐  │
│  │  Authentication & Authorization   │  │
│  └───────────────────────────────────┘  │
│  ┌───────────────────────────────────┐  │
│  │      Rate Limiting & Caching      │  │
│  └───────────────────────────────────┘  │
│  ┌───────────────────────────────────┐  │
│  │      Circuit Breaker Pattern      │  │
│  └───────────────────────────────────┘  │
│  ┌───────────────────────────────────┐  │
│  │       Request Routing Layer       │  │
│  └───────────────────────────────────┘  │
└──────┬──────────┬──────────┬───────────┘
       │          │          │
       ▼          ▼          ▼
   ┌────────┐ ┌─────────┐ ┌───────────┐
   │Backend │ │ Crawler │ │Newsletter │
   │Service │ │ Service │ │  Service  │
   └────────┘ └─────────┘ └───────────┘

Key Components

  1. Request Pipeline

    • Request logging and tracking
    • Authentication/authorization middleware
    • Input validation
    • Rate limiting
  2. Service Layer

    • Circuit breaker for fault tolerance
    • Retry logic with exponential backoff
    • Service health monitoring
  3. Cache Layer

    • Redis-backed response caching
    • Configurable TTL per endpoint
    • Cache invalidation API
  4. Monitoring

    • Real-time metrics collection
    • Circuit breaker status tracking
    • Performance monitoring

API Documentation

Interactive Documentation

Visit the Swagger UI at http://localhost:8080/api-docs for interactive API documentation.

Key Endpoints

Articles

# Get list of articles
GET /api/v1/articles?page=1&limit=20&source=state.gov

# Get single article
GET /api/v1/articles/:id

# Get related articles (vector similarity)
GET /api/v1/articles/:id/related

# Ask questions about an article (ArticleIQ)
POST /api/v1/articles/:id/qa
Content-Type: application/json

{
  "question": "What are the key points in this article?"
}

# Get bias analysis
GET /api/v1/articles/:id/bias-analysis

# Rate an article (requires authentication)
POST /api/v1/articles/:id/rate
Authorization: Bearer <token>
Content-Type: application/json

{
  "rating": 5
}

Authentication

# Register new user
POST /api/v1/auth/register
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "securePassword123",
  "name": "John Doe"
}

# Login
POST /api/v1/auth/login
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "securePassword123"
}

# Get current user profile (requires authentication)
GET /api/v1/auth/me
Authorization: Bearer <token>

Admin Endpoints

# Get metrics (admin only)
GET /api/v1/metrics
Authorization: Bearer <admin_token>

# Get circuit breaker status (admin only)
GET /api/v1/metrics/circuit-breakers
Authorization: Bearer <admin_token>

# Reset circuit breaker (admin only)
POST /api/v1/metrics/circuit-breakers/:service/reset
Authorization: Bearer <admin_token>

# Get service health status (admin only)
GET /api/v1/admin/health
Authorization: Bearer <admin_token>

# Invalidate cache (admin only)
POST /api/v1/admin/cache/invalidate
Authorization: Bearer <admin_token>
Content-Type: application/json

{
  "pattern": "articles:*"
}

Rate Limits

Endpoint Type Requests Window
Standard 100 15 min
Auth 5 15 min
Public 200 15 min

Response Format

All responses follow a consistent format:

Success Response:

{
  "success": true,
  "data": { ... },
  "timestamp": "2025-11-16T12:00:00.000Z"
}

Error Response:

{
  "success": false,
  "error": "ErrorType",
  "message": "Human-readable error message",
  "timestamp": "2025-11-16T12:00:00.000Z"
}

Deployment

Production Deployment

See DEPLOYMENT.md for detailed deployment instructions including:

  • Kubernetes deployment
  • AWS/Azure deployment
  • Environment configuration
  • Scaling strategies
  • Monitoring setup

Environment Variables

See .env.example for all available configuration options.

Development

Project Structure

API-Gateway-Service/
├── src/
│   ├── config/           # Configuration files
│   │   ├── redis.ts      # Redis client setup
│   │   ├── services.ts   # Service configurations
│   │   └── swagger.ts    # Swagger/OpenAPI setup
│   ├── middleware/       # Express middleware
│   │   ├── auth.ts       # Authentication middleware
│   │   ├── cache.ts      # Caching middleware
│   │   ├── rateLimit.ts  # Rate limiting
│   │   ├── errorHandler.ts
│   │   ├── requestLogger.ts
│   │   └── validator.ts
│   ├── routes/           # API routes
│   │   ├── index.ts      # Main router
│   │   ├── articles.ts   # Article routes
│   │   ├── auth.ts       # Auth routes
│   │   ├── crawler.ts    # Crawler routes
│   │   ├── newsletter.ts # Newsletter routes
│   │   ├── metrics.ts    # Metrics routes
│   │   └── admin.ts      # Admin routes
│   ├── services/         # Business logic
│   │   └── proxyService.ts
│   ├── utils/            # Utilities
│   │   ├── circuitBreaker.ts
│   │   ├── logger.ts
│   │   └── metrics.ts
│   ├── __tests__/        # Tests
│   └── index.ts          # Entry point
├── .github/
│   └── workflows/
│       └── ci-cd.yml     # GitHub Actions
├── docker-compose.yml    # Docker Compose config
├── Dockerfile            # Docker image
├── package.json
├── tsconfig.json
└── README.md

Testing

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

Code Quality

# Lint code
npm run lint

# Format code
npm run format

Monitoring

Health Check

curl http://localhost:8080/health

Response:

{
  "status": "healthy",
  "timestamp": "2025-11-16T12:00:00.000Z",
  "uptime": 3600,
  "environment": "production",
  "redis": "connected"
}

Metrics Endpoint

Requires admin authentication:

curl -H "Authorization: Bearer <admin_token>" \
  http://localhost:8080/api/v1/metrics

Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some 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.

Support

For support and questions:

Acknowledgments

  • Built for the SynthoraAI Content Curator ecosystem
  • Designed to help government officials access timely, summarized information
  • Part of the broader SynthoraAI platform

Made with ❤️ by the SynthoraAI Team

WebsiteDocumentationGitHub

About

API gateway service that serves as the central entry point for SynthoraAI

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •