Generate API Credentials

This is a quick guide on how to generate API credentials both through Gloo AI Studio and manually. Regardless of the method, the actual client ID and secret will be made through Gloo AI Studio, with the bearer token used being able to created manually if needed.

🖱️Creation of API Credentials + Bearer Token through Gloo AI Studio

Below is a quick gif showing how to create API credentials.

  1. Navigate to the "API Credentials" page via the sidebar in studio.
  2. If you have the "Admin" role in an organization you can create an API credential for that organization. Keep in mind that this credential will be a global API credential just for that organization. Otherwise, select "Personal Credentials" and to make a credential only associated with your user account.

  1. A new Client ID and Client Secret are generated. You can press the "Generate Token" button in the Generated Token column to create your Bearer token. This produces the pop-up on the right side where you can see the details of the token as well as its claims. Here is an example of the claims:
{
  "sub": "5tsnlxxxxxxxx1ipvsltm5n97u",
  "token_use": "access",
  "scope": "api/access",
  "auth_time": 1744836053,
  "iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_JbNXVayX2",
  "exp": 1744839653,
  "iat": 1744836053,
  "version": 2,
  "jti": "00000000-0000-0000-0000-000000000000",
  "client_id": "5tsnlxxxxxxxx1ipvsltm5n97u"
}
  • The generated token does have an expiry, but you can regenerate the token.
  1. For ease of use, you can test your new credentials with the "Test API Calls" tool at the bottom of the page. An example shown below with creating a chat and then sending a message with the newly created chat id:

⌨️ Creation of Bearer Token manually

If you are working on any sort of app, having to go into Gloo AI Studio to generate tokens will not work for you. For this, we also allow programmatic generation of tokens.

On the API Credentials page we have a quick guide if you press "Show API Instructions".

These same code examples are below. With the base url for generating these tokens being https://platform.ai.gloo.com/oauth2/token

Code Examples

import base64
import requests

def get_access_token(client_id: str, client_secret: str) -> dict:
    auth = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
    
    response = requests.post(
        "https://platform.ai.gloo.com/oauth2/token",
        headers={
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": f"Basic {auth}"
        },
        data={
            "grant_type": "client_credentials",
            "scope": "api/access"
        }
    )
    
    return response.json()

# Check token expiration
from jwt import decode
token_data = get_access_token(client_id, client_secret)
decoded = decode(token_data["access_token"], verify=False)
expiration = decoded["exp"]
curl -X POST \
  https://platform.ai.gloo.com/oauth2/token \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -u 'your_client_id:your_client_secret' \
  -d 'grant_type=client_credentials&scope=api/access'
import { Buffer } from 'buffer';

async function getAccessToken(clientId: string, clientSecret: string): Promise<string> {
  const auth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
  
  const response = await fetch(
    'https://platform.ai.gloo.com/oauth2/token',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Basic ${auth}`
      },
      body: new URLSearchParams({
        'grant_type': 'client_credentials',
        'scope': 'api/access'
      })
    }
  );

  const data = await response.json();
  
  // Check token expiration
  const decoded = JSON.parse(
    Buffer.from(data.access_token.split('.')[1], 'base64').toString()
  );
  const expiration = decoded.exp;
  
  return data.access_token;
}
require 'base64'
require 'net/http'
require 'json'
require 'jwt'

def access_token(client_id, client_secret)
  auth = Base64.strict_encode64("#{client_id}:#{client_secret}")
  
  uri = URI('https://platform.ai.gloo.com/oauth2/token')
  request = Net::HTTP::Post.new(uri)
  request['Content-Type'] = 'application/x-www-form-urlencoded'
  request['Authorization'] = "Basic #{auth}"
  request.set_form_data(
    'grant_type' => 'client_credentials',
    'scope' => 'api/access'
  )

  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
    http.request(request)
  end

  data = JSON.parse(response.body)
  
  # Check token expiration
  decoded = JWT.decode(data['access_token'], nil, false).first
  expiration = decoded['exp']
  
  data['access_token']
end
package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "net/http"
    "net/url"
    "strings"
    "time"
)

func getAccessToken(clientID, clientSecret string) (string, error) {
    auth := base64.StdEncoding.EncodeToString([]byte(clientID + ":" + clientSecret))
    
    data := url.Values{}
    data.Set("grant_type", "client_credentials")
    data.Set("scope", "api/access")
    
    req, err := http.NewRequest("POST", 
        "https://platform.ai.gloo.com/oauth2/token",
        strings.NewReader(data.Encode()))
    if err != nil {
        return "", err
    }
    
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    req.Header.Set("Authorization", "Basic " + auth)
    
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    
    var result struct {
        AccessToken string `json:"access_token"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return "", err
    }
    
    // Check token expiration from JWT payload
    parts := strings.Split(result.AccessToken, ".")
    if len(parts) != 3 {
        return "", fmt.Errorf("invalid token format")
    }
    
    var payload struct {
        Exp int64 `json:"exp"`
    }
    
    payloadBytes, _ := base64.RawURLEncoding.DecodeString(parts[1])
    json.Unmarshal(payloadBytes, &payload)
    
    expiration := time.Unix(payload.Exp, 0)
    
    return result.AccessToken, nil
}

🔔 One Important Note about Token Expiration

Access tokens expire after one hour. Monitor the token's expiration by checking the 'exp' claim in the JWT payload. Since refresh tokens are not provided with client credentials, you will need to request a new access token when the current one expires.