Scalable API Gateway Development & Integration

Job ID: 39173622

Budget: ₹600 – ₹1,500 INR

## **? Detailed Setup Guide: How to Build & Connect Everything**
This guide explains **how to build, set up, and connect all components** while ensuring the system is **scalable** for multiple users.

---

# **? System Architecture Overview**
The system consists of **4 main components**:

1️⃣ **API Gateway** (Manages API keys, subscriptions, and request validation).
2️⃣ **Subscription Bot** (Handles payments, API key generation, and user management).
3️⃣ **Software Client (Screen Capture & OCR)** (Captures screen, extracts text, and sends data to APIs).
4️⃣ **Telegram Answer Bot** (Receives AI-generated responses and sends them to users).

---

## **✅ Phase 1: Setting Up API Gateway (FastAPI + Redis + Gunicorn)**
? **Goal:** Build an **async, scalable API gateway** that **handles API keys, subscriptions, and validation**.

### **1️⃣ Installation & Setup**
#### **? Install Dependencies**
```bash
pip install fastapi uvicorn redis pymongo gunicorn python-dotenv
```
#### **? Folder Structure**
```
/api_gateway
│── api.py # Main FastAPI server
│── database.py # MongoDB & Redis setup
│── auth.py # API key validation & authentication
│── requirements.txt # Dependencies list
│── .env # API credentials & settings
```
#### **? Connect to Redis & MongoDB**
Modify `database.py`:
```python
from pymongo import MongoClient
import redis
import os

# Load environment variables
MONGO_URI = os.getenv("MONGO_URI")
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = os.getenv("REDIS_PORT", 6379)

# Connect to MongoDB
mongo_client = MongoClient(MONGO_URI)
db = mongo_client["subscription_db"]

# Connect to Redis
redis_client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, decode_responses=True)
```

---

### **2️⃣ API Gateway Endpoints & Functions**
| **Endpoint** | **Function** | **Connected Component** |
|-------------|-------------|------------------|
| `POST /generate_key` | Generates API key for a user | Telegram Subscription Bot |
| `POST /register_key` | Registers API key, deducts 1 credit | Software Client |
| `GET /subscription_check` | Checks API key validity | Software Client & Answer Bot |
| `POST /expire_key` | Expires an API key after 6 hours | Internal System |

---

#### **? Example: `POST /generate_key` (API Key Generation)**
```python
from fastapi import FastAPI
import uuid
from database import db, redis_client

app = FastAPI()

@app.post("/generate_key")
def generate_key(user_id: str):
"""Generates a unique API key for the user."""
api_key = str(uuid.uuid4())[:16] # Generate 16-char key
db["subscriptions"].insert_one({"user_id": user_id, "api_key": api_key, "credits": 10})
return {"api_key": api_key}
```
? **Redis stores API keys to avoid repeated DB queries.**

---

## **✅ Phase 2: Subscription Bot (Handles Payments & API Keys)**
? **Goal:** Set up a **Telegram bot that manages API key distribution & subscriptions**.

### **1️⃣ Installation & Setup**
#### **? Install Dependencies**
```bash
pip install telebot python-dotenv pymongo requests
```
#### **? Folder Structure**
```
/subscription_bot
│── bot.py # Main bot logic
│── database.py # MongoDB setup
│── payment.py # Payment integration (future)
│── .env # API keys & bot settings
```

---

### **2️⃣ Subscription Bot Functions**
| **Command** | **Function** | **Connected Component** |
|------------|-------------|------------------|
| `/start` | Starts bot, explains usage | User |
| `/buy_credits` | Adds credits (Mock Payment for now) | API Gateway |
| `/get_key` | Generates an API key for the user | API Gateway |

#### **? Example: `get_key` Command**
```python
import telebot
import requests
from dotenv import load_dotenv
import os

load_dotenv()
bot = telebot.TeleBot(os.getenv("TELEGRAM_BOT_TOKEN"))

@bot.message_handler(commands=['get_key'])
def get_api_key(message):
"""Fetches an API key for the user."""
response = requests.post("http://localhost:8000/generate_key", json={"user_id": message.chat.id})
api_key = response.json().get("api_key")
bot.send_message(message.chat.id, f"Your API Key: {api_key}")
```

---

## **✅ Phase 3: Software Client (Screen Capture + OCR)**
? **Goal:** Develop **a client that captures screenshots, extracts text, and sends data** to APIs.

### **1️⃣ Installation & Setup**
#### **? Install Dependencies**
```bash
pip install pyautogui opencv-python pytesseract requests python-dotenv
```
#### **? Folder Structure**
```
/software_client
│── client.py # Main script (captures screenshots, extracts text)
│── config.py # API keys & settings
│── .env # Stores API keys & interval settings
```

---

### **2️⃣ Client Functions & API Calls**
| **Function** | **Purpose** | **Connected API** |
|-------------|-------------|------------------|
| `capture_screenshot()` | Captures screen | Internal |
| `extract_text()` | Extracts text using OCR | Internal |
| `send_to_api()` | Sends extracted text to AI API | M1 API |
| `/capture` (manual) | Takes a screenshot on demand | Telegram Bot |

#### **? Example: Automated Screenshot Capture**
```python
import pyautogui
import time
import requests
import os
from dotenv import load_dotenv

load_dotenv()
API_URL = os.getenv("API_URL")

def capture_screenshot():
screenshot = pyautogui.screenshot()
screenshot.save("screenshot.png")
return "screenshot.png"

def send_to_api(image_path):
"""Sends screenshot to API."""
with open(image_path, "rb") as image:
response = requests.post(f"{API_URL}/process_image", files={"image": image})
return response.json()

while True:
img_path = capture_screenshot()
send_to_api(img_path)
time.sleep(2) # Capture every 2 seconds
```

---

## **✅ Phase 4: Answer Bot (AI Processing & Telegram Responses)**
? **Goal:** Receive processed AI results and send them to users via Telegram.

### **1️⃣ Installation & Setup**
#### **? Install Dependencies**
```bash
pip install openai telebot python-dotenv requests
```

---

### **2️⃣ Answer Bot Functions**
| **Function** | **Purpose** | **Connected Component** |
|-------------|-------------|------------------|
| `ask_openai()` | Queries OpenAI with extracted text | OpenAI API |
| `send_response()` | Sends AI response to Telegram | Telegram Bot |

#### **? Example: AI Processing & Response**
```python
import openai
import requests
import os
from dotenv import load_dotenv

load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

def ask_openai(prompt):
response = openai.ChatCompletion.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": prompt}]
)
return response["choices"][0]["message"]["content"]

def send_to_telegram(chat_id, text):
requests.post(f"https://api.telegram.org/bot{os.getenv('TELEGRAM_BOT_TOKEN')}/sendMessage",
json={"chat_id": chat_id, "text": text})
```

---

## **✅ Final Steps: Deployment & Load Testing**
✅ Deploy API Gateway (`uvicorn --host 0.0.0.0 --port 8000 --workers 4`).
✅ Deploy Subscription Bot (`python bot.py`).
✅ Deploy Answer Bot (`python answer_bot.py`).
✅ Package Client for Windows/macOS (`PyInstaller --onefile client.py`).
✅ **Load Test** using `locust -f load_test.py`.

All the details are here just need to make api gateway
Related categories: Python Software Development Coding Programming WEBDEV