Skip to content

API Specification and Documentation Plan

Hlex Helftd edited this page Oct 11, 2024 · 3 revisions

API Specification and Documentation Plan for Gateway Microservice


Table of Contents

  1. Introduction
  2. API Endpoints Definition
  3. Data Models and Schemas
  4. Error Handling Strategy
  5. API Documentation Plan
  6. API Versioning Strategy
  7. Conclusion

1. Introduction

The Gateway Microservice is a crucial component of the Zelara system, acting as the central point for handling all incoming API requests. It manages authentication and authorization, routes requests to the appropriate services, and integrates billing functionalities using Stripe. This document provides a detailed API specification and documentation plan for the Gateway Microservice, ensuring secure, efficient, and reliable communication between clients, services, and external APIs.


2. API Endpoints Definition

This section outlines all API endpoints provided by the Gateway Microservice, including HTTP methods, URL paths, descriptions, request and response formats, headers, and status codes.

2.1 Authentication and Authorization

2.1.1 Register a New User

  • Method: POST
  • URL: /api/v1/auth/register
  • Description: Registers a new user account.

Request Headers:

  • Content-Type: application/json

Request Body:

{
  "email": "[email protected]",
  "password": "UserPassword123",
  "firstName": "John",
  "lastName": "Doe"
}

Response:

  • 201 Created

    {
      "message": "User registered successfully.",
      "userId": "uuid"
    }
  • 400 Bad Request

    {
      "error": "Email already exists."
    }

2.1.2 User Login

  • Method: POST
  • URL: /api/v1/auth/login
  • Description: Authenticates a user and issues a JWT token.

Request Headers:

  • Content-Type: application/json

Request Body:

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

Response:

  • 200 OK

    {
      "message": "Login successful.",
      "token": "jwt_token",
      "expiresIn": 3600
    }
  • 401 Unauthorized

    {
      "error": "Invalid email or password."
    }

2.1.3 Refresh Token

  • Method: POST
  • URL: /api/v1/auth/refresh
  • Description: Refreshes the JWT token using a refresh token.

Request Headers:

  • Content-Type: application/json

Request Body:

{
  "refreshToken": "refresh_token"
}

Response:

  • 200 OK

    {
      "token": "new_jwt_token",
      "expiresIn": 3600
    }
  • 401 Unauthorized

    {
      "error": "Invalid refresh token."
    }

2.1.4 User Logout

  • Method: POST
  • URL: /api/v1/auth/logout
  • Description: Logs out a user and invalidates the JWT and refresh tokens.

Request Headers:

  • Authorization: Bearer jwt_token

Response:

  • 200 OK

    {
      "message": "Logged out successfully."
    }
  • 401 Unauthorized

    {
      "error": "Invalid authentication token."
    }

2.2 User Management

2.2.1 Get User Profile

  • Method: GET
  • URL: /api/v1/users/me
  • Description: Retrieves the authenticated user's profile.

Request Headers:

  • Authorization: Bearer jwt_token

Response:

  • 200 OK

    {
      "userId": "uuid",
      "email": "[email protected]",
      "firstName": "John",
      "lastName": "Doe",
      "subscriptionStatus": "active",
      "chatSessions": [
        {
          "threadId": "thread_id_example",
          "createdAt": "2024-10-11T12:00:00Z",
          "updatedAt": "2024-10-11T12:05:00Z"
        }
      ]
    }
  • 401 Unauthorized

    {
      "error": "Invalid authentication token."
    }

2.2.2 Update User Profile

  • Method: PUT
  • URL: /api/v1/users/me
  • Description: Updates the authenticated user's profile.

Request Headers:

  • Authorization: Bearer jwt_token
  • Content-Type: application/json

Request Body:

{
  "firstName": "Jane",
  "lastName": "Doe"
}

Response:

  • 200 OK

    {
      "message": "Profile updated successfully."
    }
  • 400 Bad Request

    {
      "error": "Invalid input data."
    }
  • 401 Unauthorized

    {
      "error": "Invalid authentication token."
    }

2.3 Subscription and Billing

2.3.1 Get Subscription Status

  • Method: GET
  • URL: /api/v1/subscriptions/status
  • Description: Retrieves the user's subscription status.

Request Headers:

  • Authorization: Bearer jwt_token

Response:

  • 200 OK

    {
      "subscriptionStatus": "active",
      "plan": "premium",
      "expiresOn": "2025-12-31T23:59:59Z"
    }
  • 401 Unauthorized

    {
      "error": "Invalid authentication token."
    }

2.3.2 Upgrade Subscription

  • Method: POST
  • URL: /api/v1/subscriptions/upgrade
  • Description: Initiates a subscription upgrade process.

Request Headers:

  • Authorization: Bearer jwt_token
  • Content-Type: application/json

Request Body:

{
  "plan": "premium"
}

Response:

  • 200 OK

    {
      "message": "Subscription upgrade initiated.",
      "checkoutUrl": "https://checkout.stripe.com/pay/cs_test_..."
    }
  • 400 Bad Request

    {
      "error": "Invalid plan selected."
    }
  • 401 Unauthorized

    {
      "error": "Invalid authentication token."
    }

2.3.3 Stripe Webhook

  • Method: POST
  • URL: /api/v1/subscriptions/webhook
  • Description: Endpoint for Stripe to send webhook events.

Request Headers:

  • Stripe-Signature: signature

Request Body:

  • Stripe event payload.

Response:

  • 200 OK

2.4 Chat Session Management

2.4.1 Initialize Chat Session

  • Method: POST
  • URL: /api/v1/chat/init
  • Description: Initializes a new chat session by invoking Zelara-GPT via the Gateway, which in turn creates a thread using the OpenAI Assistant API.

Request Headers:

  • Authorization: Bearer jwt_token

Response:

  • 201 Created

    {
      "message": "Chat session initialized.",
      "threadId": "thread_id_example"
    }
  • 401 Unauthorized

    {
      "error": "Invalid authentication token."
    }

2.4.2 List Chat Sessions

  • Method: GET
  • URL: /api/v1/chat/sessions
  • Description: Retrieves a list of the user's chat sessions stored in the UserDB.

Request Headers:

  • Authorization: Bearer jwt_token

Response:

  • 200 OK

    {
      "chatSessions": [
        {
          "threadId": "thread_id_example",
          "createdAt": "2024-10-11T12:00:00Z",
          "updatedAt": "2024-10-11T12:05:00Z"
        },
        {
          "threadId": "another_thread_id",
          "createdAt": "2024-10-10T15:30:00Z",
          "updatedAt": "2024-10-10T16:00:00Z"
        }
      ]
    }
  • 401 Unauthorized

    {
      "error": "Invalid authentication token."
    }

2.4.3 Close Chat Session

  • Method: DELETE
  • URL: /api/v1/chat/{threadId}
  • Description: Closes an existing chat session.

Request Headers:

  • Authorization: Bearer jwt_token

Path Parameters:

  • threadId: The ID of the chat session.

Response:

  • 200 OK

    {
      "message": "Chat session closed successfully.",
      "threadId": "thread_id_example"
    }
  • 404 Not Found

    {
      "error": "Chat session not found."
    }
  • 401 Unauthorized

    {
      "error": "Invalid authentication token."
    }

3. Data Models and Schemas

This section defines the data models and schemas for requests and responses using JSON Schema.

3.1 User Model

{
  "type": "object",
  "properties": {
    "userId": { "type": "string", "format": "uuid" },
    "email": { "type": "string", "format": "email" },
    "firstName": { "type": "string" },
    "lastName": { "type": "string" },
    "subscriptionStatus": { "type": "string", "enum": ["active", "inactive", "pending"] },
    "chatSessions": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "threadId": { "type": "string" },
          "createdAt": { "type": "string", "format": "date-time" },
          "updatedAt": { "type": "string", "format": "date-time" }
        },
        "required": ["threadId", "createdAt", "updatedAt"]
      }
    },
    "createdAt": { "type": "string", "format": "date-time" },
    "updatedAt": { "type": "string", "format": "date-time" }
  },
  "required": ["userId", "email", "subscriptionStatus", "createdAt", "updatedAt"],
  "additionalProperties": false
}

3.2 Authentication Models

Register Request Schema

{
  "type": "object",
  "properties": {
    "email": { "type": "string", "format": "email" },
    "password": { "type": "string", "minLength": 8 },
    "firstName": { "type": "string" },
    "lastName": { "type": "string" }
  },
  "required": ["email", "password", "firstName", "lastName"],
  "additionalProperties": false
}

Login Request Schema

{
  "type": "object",
  "properties": {
    "email": { "type": "string", "format": "email" },
    "password": { "type": "string" }
  },
  "required": ["email", "password"],
  "additionalProperties": false
}

3.3 Subscription Models

Subscription Status Schema

{
  "type": "object",
  "properties": {
    "subscriptionStatus": { "type": "string", "enum": ["active", "inactive", "pending", "cancelled"] },
    "plan": { "type": "string", "enum": ["free", "basic", "premium"] },
    "expiresOn": { "type": "string", "format": "date-time" }
  },
  "required": ["subscriptionStatus", "plan"],
  "additionalProperties": false
}

3.4 Chat Models

Chat Session Schema

{
  "type": "object",
  "properties": {
    "threadId": { "type": "string" },
    "createdAt": { "type": "string", "format": "date-time" },
    "updatedAt": { "type": "string", "format": "date-time" }
  },
  "required": ["threadId", "createdAt", "updatedAt"],
  "additionalProperties": false
}

4. Error Handling Strategy

4.1 Standard Error Codes and Messages

Status Code Error Code Message
400 INVALID_REQUEST The request could not be understood or was missing required parameters.
401 UNAUTHORIZED Authentication failed or user does not have permissions for the desired action.
403 FORBIDDEN Access forbidden.
404 NOT_FOUND Resource not found or chat session not found.
409 CONFLICT Conflict in the request.
429 TOO_MANY_REQUESTS Too many requests. Rate limit exceeded.
500 INTERNAL_SERVER_ERROR An error occurred on the server.

4.2 Exception Handling Procedures

  • Input Validation Errors:

    • Return 400 Bad Request with error code INVALID_REQUEST.
    • Include details about the invalid parameters.
  • Authentication Errors:

    • Return 401 Unauthorized with error code UNAUTHORIZED.
    • Prompt the user to re-authenticate.
  • Authorization Errors:

    • Return 403 Forbidden with error code FORBIDDEN.
    • Inform the user they do not have access to the resource.
  • Resource Not Found:

    • Return 404 Not Found with error code NOT_FOUND.
    • Indicate that the requested resource or chat session does not exist.
  • Conflict Errors:

    • Return 409 Conflict with error code CONFLICT.
    • Provide details about the conflict.
  • Rate Limiting:

    • Return 429 Too Many Requests with error code TOO_MANY_REQUESTS.
    • Include information on when the user can retry.
  • Server Errors:

    • Return 500 Internal Server Error with error code INTERNAL_SERVER_ERROR.
    • Do not expose internal error details to the client.
    • Log the error internally for debugging.

5. API Documentation Plan

5.1 Documentation Tools

  • OpenAPI Specification (Swagger):

    • Utilize OpenAPI Specification version 3.0 or higher.
    • Define all endpoints, parameters, request/response schemas, and examples.
  • Swagger UI:

    • Host interactive API documentation using Swagger UI at /api-docs.
    • Allow developers to explore and test API endpoints.

5.2 Maintaining Up-to-Date Documentation

  • Automated Documentation Generation:

    • Integrate tools like swagger-jsdoc to generate documentation from code annotations.
    • Ensure that any changes to the API are reflected in the documentation automatically.
  • Continuous Integration:

    • Include documentation validation in the CI/CD pipeline.
    • Fail builds if the documentation is not up-to-date or contains errors.
  • Version Control:

    • Store the OpenAPI specification files in the same repository as the code.
    • Use version control practices to track changes to the API and documentation.
  • Developer Guidelines:

    • Establish coding standards that require updates to the API documentation when code changes are made.
    • Include documentation updates as part of the code review process.

6. API Versioning Strategy

6.1 Versioning Approach

  • URL Path Versioning:

    • Include the version number in the base URL of the API endpoints.
    • Example: /api/v1/, /api/v2/
  • Semantic Versioning:

    • Follow semantic versioning principles:
      • MAJOR: Incompatible API changes.
      • MINOR: Backward-compatible functionality.
      • PATCH: Backward-compatible bug fixes.

6.2 Deprecation Policy

  • Advance Notice:

    • Provide at least 6 months notice before deprecating an API version.

    • Communicate via:

      • API response headers (e.g., Deprecation and Link headers).
      • Email notifications to registered developers.
      • Updates in the API documentation.
  • Support for Deprecated Versions:

    • Maintain deprecated API versions during the deprecation period.
    • Provide support and critical fixes if necessary.
  • Documentation:

    • Clearly mark deprecated endpoints in the documentation.
    • Provide migration guides to help developers transition to newer versions.

7. Conclusion

This API Specification and Documentation Plan provides a comprehensive outline of the Gateway Microservice's API, ensuring that it meets enterprise-level standards for functionality, security, and maintainability. By adhering to this plan, developers can ensure consistent, reliable, and user-friendly interactions with the Zelara platform.


Prepared by: Hlex Helftd, Lead Developer

Date: 2024-10-12


Note: This document should be reviewed and updated regularly to reflect any changes in the API or project requirements. It serves as a guide for developers, stakeholders, and team members to understand the API's structure and design decisions.


Appendices

A. Sample API Requests and Responses

A.1 Register a New User

Request:

POST /api/v1/auth/register HTTP/1.1
Host: api.zelara.com
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "SecurePass123",
  "firstName": "New",
  "lastName": "User"
}

Response:

HTTP/1.1 201 Created
Content-Type: application/json

{
  "message": "User registered successfully.",
  "userId": "123e4567-e89b-12d3-a456-426614174000"
}

A.2 User Login

Request:

POST /api/v1/auth/login HTTP/1.1
Host: api.zelara.com
Content-Type: application/json

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

Response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "message": "Login successful.",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresIn": 3600
}

A.3 Initialize Chat Session

Request:

POST /api/v1/chat/init HTTP/1.1
Host: api.zelara.com
Authorization: Bearer jwt_access_token

Response:

HTTP/1.1 201 Created
Content-Type: application/json

{
  "message": "Chat session initialized.",
  "threadId": "thread_id_example"
}

A.4 List Chat Sessions

Request:

GET /api/v1/chat/sessions HTTP/1.1
Host: api.zelara.com
Authorization: Bearer jwt_access_token

Response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "chatSessions": [
    {
      "threadId": "thread_id_example",
      "createdAt": "2024-10-11T12:00:00Z",
      "updatedAt": "2024-10-11T12:05:00Z"
    },
    {
      "threadId": "another_thread_id",
      "createdAt": "2024-10-10T15:30:00Z",
      "updatedAt": "2024-10-10T16:00:00Z"
    }
  ]
}

A.5 Close Chat Session

Request:

DELETE /api/v1/chat/thread_id_example HTTP/1.1
Host: api.zelara.com
Authorization: Bearer jwt_access_token

Response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "message": "Chat session closed successfully.",
  "threadId": "thread_id_example"
}

B. References


Notes:

  • After initializing a chat session, clients will communicate directly with the OpenAI Assistant API using the threadId provided. The Gateway does not handle chat messages after session initialization.
  • Ensure consistent use of terms like "threadId", "Zelara-GPT", and "OpenAI Assistant API" throughout the documentation.
  • All interactions must comply with OpenAI's policies and usage guidelines.

Please ensure that all development and integration efforts align with this specification. For questions or clarifications, contact the API development team at [email protected].


End of Document