Backend API Reference

Complete API endpoints reference

Backend API Reference

Complete reference for all backend-api endpoints with request/response examples.

Base URL

Development: http://localhost:3000/api
Production: https://your-railway-url.up.railway.app/api

Authentication

Most endpoints require JWT authentication. Include the token in the Authorization header:

Authorization: Bearer <your-jwt-token>

Health & Status Endpoints

GET /health

Check backend API health status.

Authentication: Not required

Request:

curl http://localhost:3000/api/health

Response (200 OK):

{
  "status": "ok",
  "timestamp": "2025-01-15T12:00:00.000Z",
  "service": "backend-api",
  "version": "1.0.0"
}

GET /

Get root API information.

Authentication: Not required

Request:

curl http://localhost:3000/api

Response (200 OK):

{
  "message": "BACKEND API IS RUNNING!!"
}

Authentication Endpoints

POST /auth/register

Register a new user account.

Authentication: Not required

Request Body:

{
  email: string;      // Valid email address
  password: string;   // Minimum 6 characters
  name: string;       // User's full name
}

Example Request:

curl -X POST http://localhost:3000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "SecurePass123!",
    "name": "John Doe"
  }'

Response (201 Created):

{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "507f1f77bcf86cd799439011",
    "email": "[email protected]",
    "name": "John Doe",
    "roles": ["user"],
    "createdAt": "2025-01-15T12:00:00.000Z"
  }
}

Error Responses:

// 409 Conflict - Email already exists
{
  "statusCode": 409,
  "message": "User with this email already exists",
  "error": "Conflict"
}

// 400 Bad Request - Invalid data
{
  "statusCode": 400,
  "message": ["email must be a valid email"],
  "error": "Bad Request"
}

POST /auth/login

Login with existing user credentials.

Authentication: Not required

Request Body:

{
  email: string;      // Registered email address
  password: string;   // User's password
}

Example Request:

curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "SecurePass123!"
  }'

Response (200 OK):

{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "507f1f77bcf86cd799439011",
    "email": "[email protected]",
    "name": "John Doe",
    "roles": ["user"],
    "createdAt": "2025-01-15T12:00:00.000Z"
  }
}

Error Responses:

// 401 Unauthorized - Invalid credentials
{
  "statusCode": 401,
  "message": "Invalid credentials",
  "error": "Unauthorized"
}

GET /auth/profile

Get current user profile information.

Authentication: Required (JWT token)

Example Request:

TOKEN="your-jwt-token-here"

curl http://localhost:3000/api/auth/profile \
  -H "Authorization: Bearer $TOKEN"

Response (200 OK):

{
  "id": "507f1f77bcf86cd799439011",
  "email": "[email protected]",
  "name": "John Doe",
  "roles": ["user"],
  "createdAt": "2025-01-15T12:00:00.000Z"
}

Error Responses:

// 401 Unauthorized - Missing or invalid token
{
  "statusCode": 401,
  "message": "Unauthorized",
  "error": "Unauthorized"
}

AI Service Endpoints

All AI endpoints require authentication.

POST /ai/openai/chat

Send chat completion request to OpenAI.

Authentication: Required (JWT token)

Request Body:

{
  messages: Array<{
    role: 'user' | 'assistant' | 'system';
    content: string;
  }>;
  model?: string;          // Default: 'gpt-4o-mini'
  temperature?: number;    // 0-2, Default: 0.7
  maxTokens?: number;      // Default: 1000
}

Example Request:

TOKEN="your-jwt-token-here"

curl -X POST http://localhost:3000/api/ai/openai/chat \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    "model": "gpt-4o-mini",
    "temperature": 0.7,
    "maxTokens": 500
  }'

Response (200 OK):

{
  "text": "Quantum computing is...",
  "usage": {
    "promptTokens": 25,
    "completionTokens": 150,
    "totalTokens": 175
  },
  "model": "gpt-4o-mini",
  "provider": "openai",
  "cost": 0.000035,
  "requestId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}

POST /ai/anthropic/messages

Send message request to Anthropic Claude.

Authentication: Required (JWT token)

Request Body:

{
  messages: Array<{
    role: 'user' | 'assistant';
    content: string;
  }>;
  model?: string;          // Default: 'claude-3-5-sonnet-20241022'
  temperature?: number;    // 0-1, Default: 0.7
  maxTokens?: number;      // Default: 1000
}

Example Request:

TOKEN="your-jwt-token-here"

curl -X POST http://localhost:3000/api/ai/anthropic/messages \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "messages": [
      {"role": "user", "content": "What is machine learning?"}
    ],
    "model": "claude-3-5-sonnet-20241022",
    "maxTokens": 500
  }'

Response (200 OK):

{
  "text": "Machine learning is...",
  "usage": {
    "promptTokens": 15,
    "completionTokens": 200,
    "totalTokens": 215
  },
  "model": "claude-3-5-sonnet-20241022",
  "provider": "anthropic",
  "cost": 0.000645,
  "requestId": "b2c3d4e5-f6g7-8901-bcde-fg2345678901"
}

POST /ai/google/generate

Generate content using Google Gemini.

Authentication: Required (JWT token)

Request Body:

{
  messages: Array<{
    role: 'user' | 'assistant';
    content: string;
  }>;
  model?: string;          // Default: 'gemini-pro'
  temperature?: number;    // 0-2, Default: 0.9
  maxTokens?: number;      // Default: 1000
}

Example Request:

TOKEN="your-jwt-token-here"

curl -X POST http://localhost:3000/api/ai/google/generate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "messages": [
      {"role": "user", "content": "Write a haiku about programming."}
    ],
    "model": "gemini-pro",
    "maxTokens": 100
  }'

Response (200 OK):

{
  "text": "Code flows like water\nBugs hide in shadows unseen\nDebug, find, fix, repeat",
  "usage": {
    "promptTokens": 10,
    "completionTokens": 20,
    "totalTokens": 30
  },
  "model": "gemini-pro",
  "provider": "google",
  "cost": 0.000015,
  "requestId": "c3d4e5f6-g7h8-9012-cdef-gh3456789012"
}

Analytics Endpoints

GET /ai/usage

Get user's AI usage statistics.

Authentication: Required (JWT token)

Query Parameters:

Example Request:

TOKEN="your-jwt-token-here"

curl "http://localhost:3000/api/ai/usage?days=30" \
  -H "Authorization: Bearer $TOKEN"

Response (200 OK):

{
  "totalRequests": 150,
  "totalTokens": 45000,
  "totalCost": 0.135
}

GET /ai/usage/providers

Get breakdown of usage by provider and model.

Authentication: Required (JWT token)

Query Parameters:

Example Request:

TOKEN="your-jwt-token-here"

curl "http://localhost:3000/api/ai/usage/providers?days=30" \
  -H "Authorization: Bearer $TOKEN"

Response (200 OK):

[
  {
    "provider": "openai",
    "model": "gpt-4o-mini",
    "requestCount": 75,
    "totalTokens": 22500,
    "cost": 0.0675
  },
  {
    "provider": "anthropic",
    "model": "claude-3-5-sonnet-20241022",
    "requestCount": 50,
    "totalTokens": 15000,
    "cost": 0.045
  },
  {
    "provider": "google",
    "model": "gemini-pro",
    "requestCount": 25,
    "totalTokens": 7500,
    "cost": 0.0225
  }
]

MongoDB Storage Endpoints

POST /storage/mongodb/test

Test MongoDB connection and get cluster information.

Authentication: Required (JWT token)

Request Body:

{
  connectionString: string;  // MongoDB connection string
  database: string;          // Database name
}

Example Request:

TOKEN="your-jwt-token-here"

curl -X POST http://localhost:3000/api/storage/mongodb/test \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "connectionString": "mongodb+srv://user:[email protected]/",
    "database": "gograb-api"
  }'

Response (200 OK):

{
  "success": true,
  "clusterName": "gograbspace",
  "version": "7.0.0",
  "latency": 847,
  "databases": ["gograb-api", "admin", "local"]
}

POST /storage/mongodb/query

Query documents from a MongoDB collection.

Authentication: Required (JWT token)

Request Body:

{
  connectionString: string;
  database: string;
  collection: string;
  filter?: object;         // MongoDB filter query
  limit?: number;          // Default: 100
}

Example Request:

TOKEN="your-jwt-token-here"

curl -X POST http://localhost:3000/api/storage/mongodb/query \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "connectionString": "mongodb+srv://user:[email protected]/",
    "database": "gograb-api",
    "collection": "users",
    "filter": {"email": "[email protected]"},
    "limit": 10
  }'

Response (200 OK):

{
  "success": true,
  "documents": [
    {
      "_id": "507f1f77bcf86cd799439011",
      "email": "[email protected]",
      "name": "John Doe",
      "createdAt": "2025-01-15T12:00:00.000Z"
    }
  ],
  "count": 1
}

Rate Limiting

All endpoints are rate-limited to prevent abuse:

When rate limit is exceeded:

{
  "statusCode": 429,
  "message": "Too Many Requests",
  "error": "ThrottlerException"
}

Error Responses

Standard Error Format

All errors follow this format:

{
  "statusCode": number,
  "message": string | string[],
  "error": string
}

Common HTTP Status Codes

Best Practices

Authentication

  1. Store JWT token securely (not in localStorage for production)
  2. Include token in all authenticated requests
  3. Handle token expiration (7 days by default)
  4. Refresh token before expiration

Error Handling

try {
  const response = await fetch('/api/endpoint', {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message);
  }

  return await response.json();
} catch (error) {
  console.error('API Error:', error);
  // Handle error appropriately
}

Rate Limiting

  1. Implement exponential backoff for rate limit errors
  2. Cache responses when possible
  3. Monitor rate limit headers
  4. Batch requests when appropriate

Next Steps