Gate/AI Integration Guide

Benefits of Using Gate/AI

  • Secure API key management Critical
  • Rate limiting and usage monitoring Critical
  • Unified Authentication API across multiple providers (OpenAI, Anthropic, Google Gemini)
  • Request analytics and performance metrics

What you need to do

Integration with Gate/AI requires just 3 simple changes to your existing mobile app:

1

Change your API endpoint

Replace your provider's API URL with your Gate/AI endpoint.
E.g., switch api.openai.com to [your-gate-name].us01.gate-ai.net

2

Add OAuth authentication with Gate/AI

Get a token from /oauth/token using your client secret. The token lasts for an hour. Store this locally if performing multiple requests.

3

Add the token as an Authentication header

Set an Authentication Bearer header.

That's it! The same URIs work. Gate/AI will forward your exact request on to the provider and stream the response back to you.

Authentication

Gate/AI uses token-based OAuth authentication. You'll need your client secret from your gate configuration to obtain access tokens.

Authentication Flow

  1. 1. Request a token using your client_secret, specifying your client_id and grant_type.
  2. 2. Include the token in the Authorization header for API requests
  3. 3. Tokens are valid for 60 minutes.
  4. 4. Once expired, requst another token.

Using Gate/AI is mostly a drop-in solution. The authentication piece is the only less-simple part. In the code examples, we provide a sample one-shot function getGateAIToken() for returning a token and saving it for later use. You can drop it right into your codebase or use it as a starting point.

Analytics

Gate/AI provides analytics through information collection during the authentication process. When obtaining an auth token, set values for these headers to allow Gate/AI to provide insights into API usage patterns and client behavior.

Supported Headers

The following headers are automatically collected when you request an auth token. You simply need to set them. See the example code (Advanced Token Creation) for an authentication function that uses these headers.

  • X-Client-Locale: Language and country code. E.g., es-MX or es-ES
  • X-App-Version: The version of your app in use. E.g., 1.0
  • X-OS-Version: The version of the OS running. E.g., 15.6
  • X-User-Status: Whatever you want. It could be the subscription plan in use. Or simply Paid vs Free.
  • X-Device-Identifier: The unique identifier of the device your app received. Used to unique identify abuse from a specific person, beyond IP Address.
  • X-Device-Type: The manufacturer of the device.

Privacy & Data Handling

All analytics data is processed in compliance with privacy standards. No personally identifiable information is stored.

Code Examples

Choose your AI provider:

Choose your platform:

iOS (Swift) Code Examples

Before: Direct OpenAI Integration

// Original OpenAI integration
let url = URL(string: "https://api.openai.com/v1/chat/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("Bearer \(openAIKey)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

After: Gate/AI Integration

// Step 1: Get Gate/AI token with caching
func getGateAIToken() async throws -> String {
    // Check for cached token first
    let userDefaults = UserDefaults.standard
    if let cachedToken = userDefaults.string(forKey: "gateai_access_token"),
       let expirationDate = userDefaults.object(forKey: "gateai_token_expiration") as? Date,
       Date().addingTimeInterval(10) < expirationDate { // 10 second buffer
        return cachedToken
    }

    // Request new token
    let tokenURL = URL(string: "https://your-gate.gateai.com/oauth/token")!
    var tokenRequest = URLRequest(url: tokenURL)
    tokenRequest.httpMethod = "POST"
    tokenRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

    let tokenBody = ["client_secret": "your-client-secret"]
    tokenRequest.httpBody = try JSONSerialization.data(withJSONObject: tokenBody)

    let (data, _) = try await URLSession.shared.data(for: tokenRequest)
    let response = try JSONDecoder().decode(TokenResponse.self, from: data)

    // Cache the token and expiration
    let expirationDate = Date().addingTimeInterval(TimeInterval(response.expires_in))
    userDefaults.set(response.access_token, forKey: "gateai_access_token")
    userDefaults.set(expirationDate, forKey: "gateai_token_expiration")

    return response.access_token
}

// Step 2: Use Gate/AI endpoint (same OpenAI-compatible API)
let token = try await getGateAIToken()
let url = URL(string: "https://your-gate.gateai.com/v1/chat/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

Advanced: Enhanced Token Creation

You can include additional metadata when requesting tokens for enhanced monitoring and analytics:

func getGateAITokenWithMetadata() async throws -> String {
    // Check for cached token first
    let userDefaults = UserDefaults.standard
    if let cachedToken = userDefaults.string(forKey: "gateai_access_token"),
       let expirationDate = userDefaults.object(forKey: "gateai_token_expiration") as? Date,
       Date().addingTimeInterval(10) < expirationDate { // 10 second buffer
        return cachedToken
    }

    // Request new token with enhanced metadata
    let tokenURL = URL(string: "https://your-gate.gateai.com/oauth/token")!
    var tokenRequest = URLRequest(url: tokenURL)
    tokenRequest.httpMethod = "POST"
    tokenRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

    // Get system information dynamically
    let locale = Locale.current.identifier
    let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
    let osVersion = "\(UIDevice.current.systemName) \(UIDevice.current.systemVersion)"
    let deviceId = UIDevice.current.identifierForVendor?.uuidString ?? "unknown"
    let deviceType = UIDevice.current.name // Device model name (e.g., "iPhone", "iPad")

    // Enhanced metadata headers with system values
    tokenRequest.addValue(locale, forHTTPHeaderField: "x-client-locale")
    tokenRequest.addValue(appVersion, forHTTPHeaderField: "x-app-version")
    tokenRequest.addValue(osVersion, forHTTPHeaderField: "x-os-version")
    tokenRequest.addValue("premium", forHTTPHeaderField: "x-user-status") // Set based on your user logic
    tokenRequest.addValue(deviceId, forHTTPHeaderField: "x-device-identifier")
    tokenRequest.addValue(deviceType, forHTTPHeaderField: "x-device-type")

    let tokenBody = ["client_secret": "your-client-secret"]
    tokenRequest.httpBody = try JSONSerialization.data(withJSONObject: tokenBody)

    let (data, _) = try await URLSession.shared.data(for: tokenRequest)
    let response = try JSONDecoder().decode(TokenResponse.self, from: data)

    // Cache the token and expiration
    let expirationDate = Date().addingTimeInterval(TimeInterval(response.expires_in))
    userDefaults.set(response.access_token, forKey: "gateai_access_token")
    userDefaults.set(expirationDate, forKey: "gateai_token_expiration")

    return response.access_token
}