This tutorial covers how to authenticate with the Gloo AI API using OAuth2 client credentials flow. Authentication is required for all API endpoints and involves exchanging your Client ID and Client Secret for a temporary access token.

Overview

The Gloo AI API uses OAuth2 client credentials flow for authentication. This process involves:
  1. Get Client Credentials - Obtain your Client ID and Client Secret from the Gloo AI Studio
  2. Exchange for Access Token - Use your credentials to get a temporary bearer token
  3. Use Token in API Calls - Include the bearer token in all API requests
  4. Handle Token Expiration - Refresh tokens when they expire

Prerequisites

Before starting, ensure you have:

Step 1: Environment Setup

First, set up your environment variables to securely store your credentials:

Environment Variables

Create a .env file in your project root:
GLOO_CLIENT_ID=your_actual_client_id_here
GLOO_CLIENT_SECRET=your_actual_client_secret_here
For Go and Java, you can also export them directly:
export GLOO_CLIENT_ID="your_actual_client_id_here"
export GLOO_CLIENT_SECRET="your_actual_client_secret_here"

Step 2: Token Exchange

Exchange your Client ID and Client Secret for an access token by calling the OAuth2 token endpoint:
import requests
import time
import os
from dotenv import load_dotenv

load_dotenv()

CLIENT_ID = os.getenv("GLOO_CLIENT_ID", "YOUR_CLIENT_ID")
CLIENT_SECRET = os.getenv("GLOO_CLIENT_SECRET", "YOUR_CLIENT_SECRET")
TOKEN_URL = "https://platform.ai.gloo.com/oauth2/token"

def get_access_token():
    """Retrieve a new access token from the Gloo AI API."""
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    data = {"grant_type": "client_credentials", "scope": "api/access"}

    response = requests.post(TOKEN_URL, headers=headers, data=data, auth=(CLIENT_ID, CLIENT_SECRET))
    response.raise_for_status()

    token_data = response.json()
    token_data['expires_at'] = int(time.time()) + token_data['expires_in']

    return token_data

# Example usage
token_info = get_access_token()
print(f"Access token: {token_info['access_token']}")
print(f"Expires in: {token_info['expires_in']} seconds")

Step 3: Token Management

Access tokens are temporary and expire after a certain period. Implement token management to handle expiration:
# Global token storage
access_token_info = {}

def is_token_expired(token_info):
    """Check if the token is expired or close to expiring."""
    if not token_info or 'expires_at' not in token_info:
        return True
    return time.time() > (token_info['expires_at'] - 60)

def ensure_valid_token():
    """Ensure we have a valid access token."""
    global access_token_info
    if is_token_expired(access_token_info):
        print("Getting new access token...")
        access_token_info = get_access_token()
    return access_token_info['access_token']

# Usage in API calls
def make_api_call():
    token = ensure_valid_token()
    headers = {"Authorization": f"Bearer {token}"}
    # Make your API call here

Step 4: Using Tokens in API Calls

Once you have a valid access token, include it in the Authorization header of your API requests:
Authorization: Bearer YOUR_ACCESS_TOKEN

Example API Request

import requests

def make_authenticated_request(endpoint, payload=None):
    """Make an authenticated API request."""
    token = ensure_valid_token()

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }

    if payload:
        response = requests.post(endpoint, headers=headers, json=payload)
    else:
        response = requests.get(endpoint, headers=headers)

    response.raise_for_status()
    return response.json()

# Example usage
result = make_authenticated_request(
    "https://platform.ai.gloo.com/ai/v1/chat/completions",
    {
        "model": "us.anthropic.claude-sonnet-4-20250514-v1:0",
        "messages": [{"role": "user", "content": "Hello!"}]
    }
)

Security Best Practices

1. Environment Variables

  • Never hardcode credentials in your source code
  • Use environment variables or secure credential storage
  • Add .env files to your .gitignore

2. Token Storage

  • Store tokens securely in memory
  • Don’t persist tokens to disk in production
  • Implement proper token rotation

3. Network Security

  • Always use HTTPS for API calls
  • Implement proper error handling
  • Use secure HTTP client configurations

4. Error Handling

  • Handle authentication failures gracefully
  • Implement retry logic for transient failures
  • Log authentication events securely

Common Issues and Solutions

Issue: 401 Unauthorized

Cause: Token expired or invalid credentials Solution: Implement token refresh logic and verify credentials

Issue: 403 Forbidden

Cause: Insufficient permissions Solution: Check your API access levels in the Studio

Issue: Token Expired

Cause: Access token has exceeded its lifetime Solution: Implement automatic token refresh before expiration

Testing Your Implementation

Create a simple test to verify your authentication setup:
def test_authentication():
    """Test authentication flow."""
    try:
        # Test token retrieval
        token_info = get_access_token()
        print(f"✓ Token retrieved successfully")
        print(f"  Token type: {token_info.get('token_type')}")
        print(f"  Expires in: {token_info.get('expires_in')} seconds")

        # Test token validation
        token = ensure_valid_token()
        print(f"✓ Token validation successful")

        return True
    except Exception as e:
        print(f"✗ Authentication failed: {e}")
        return False

if __name__ == "__main__":
    test_authentication()

Next Steps

Now that you have authentication set up, you can use it in other Gloo AI tutorials:
  1. Building Interactive Chat - Create conversational experiences
  2. Using the Completions API - Generate text completions
  3. API Reference - Explore all available endpoints
The authentication patterns shown here work across all Gloo AI API endpoints, providing a secure foundation for your applications.