Skip to main content

Python API Client

Glean's Python API client provides a Pythonic interface to Glean's Client API, making it easy to integrate enterprise search and AI capabilities into your Python applications.

glean-api-client

Official Python client for Glean's Client API

info

Authentication Required: You'll need a Client API token to use this library.

Installation

pip install glean-api-client

Quick Start

1

Set up environment variables

export GLEAN_INSTANCE="your-company"
export GLEAN_API_TOKEN="your-token-here"
2

Basic usage

from glean.api_client import Glean
import os

with Glean(
api_token=os.getenv("GLEAN_API_TOKEN"),
instance=os.getenv("GLEAN_INSTANCE"),
) as client:
response = client.client.chat.create(
messages=[{
"fragments": [{"text": "What are our company values?"}]
}],
timeout_millis=30000
)
print(response)

Core Features

Chat API

Build conversational AI applications:

# Simple chat
response = client.client.chat.create(
messages=[{"fragments": [{"text": "Explain our Q4 strategy"}]}]
)

# Streaming chat for real-time responses
for chunk in client.client.chat.stream(
messages=[{"fragments": [{"text": "What are our priorities?"}]}]
):
print(chunk.text, end="", flush=True)

Search API

Integrate enterprise search:

results = client.client.search.search(
query="quarterly business review",
page_size=10
)

for result in results.results:
print(f"Title: {result.title}")
print(f"URL: {result.url}")

Agents API

Execute pre-built agents:

response = client.client.agents.create_and_wait_run(
agent_id="your-agent-id",
inputs={"query": "Analyze sales performance"}
)

Framework Integrations

FastAPI

from fastapi import FastAPI
from glean.api_client import Glean
from pydantic import BaseModel

app = FastAPI()

class ChatRequest(BaseModel):
message: str

@app.post("/chat")
async def chat_endpoint(request: ChatRequest):
with Glean(
api_token=os.getenv("GLEAN_API_TOKEN"),
instance=os.getenv("GLEAN_INSTANCE"),
) as client:
response = client.client.chat.create(
messages=[{"fragments": [{"text": request.message}]}]
)
return {"response": response.text}

Django

from django.http import JsonResponse
from glean.api_client import Glean
import json

def chat_view(request):
data = json.loads(request.body)
message = data.get('message')

with Glean(
api_token=os.getenv("GLEAN_API_TOKEN"),
instance=os.getenv("GLEAN_INSTANCE"),
) as client:
response = client.client.chat.create(
messages=[{"fragments": [{"text": message}]}]
)

return JsonResponse({'response': response.text})

Streamlit

import streamlit as st
from glean.api_client import Glean

st.title("Company Knowledge Assistant")

user_input = st.text_input("Ask a question:")

if user_input:
with Glean(
api_token=os.getenv("GLEAN_API_TOKEN"),
instance=os.getenv("GLEAN_INSTANCE"),
) as client:
response = client.client.chat.create(
messages=[{"fragments": [{"text": user_input}]}]
)
st.write(response.text)

Authentication

client = Glean(
api_token="your-user-token",
instance="your-company"
)

Global Tokens with ActAs

response = client.client.chat.create(
messages=[{"fragments": [{"text": "Hello"}]}],
headers={"X-Glean-ActAs": "user@company.com"}
)

OAuth Authentication

OAuth allows you to use access tokens from your identity provider (Google, Azure, Okta, etc.) instead of Glean-issued tokens.

Prerequisites

OAuth requests require these headers:

HeaderValue
AuthorizationBearer <oauth_access_token>
X-Glean-Auth-TypeOAUTH

Example: Authorization Code Flow

This example uses Authlib with Flask:

import os
import httpx
from flask import Flask, redirect, request, jsonify
from authlib.integrations.flask_client import OAuth
from glean.api_client import Glean
from glean.api_client import models

app = Flask(__name__)
app.secret_key = os.urandom(24)

oauth = OAuth(app)
oauth.register(
name='provider',
client_id=os.getenv('OAUTH_CLIENT_ID'),
client_secret=os.getenv('OAUTH_CLIENT_SECRET'),
server_metadata_url=os.getenv('OAUTH_ISSUER') + '/.well-known/openid-configuration',
client_kwargs={'scope': 'openid email'},
code_challenge_method='S256', # Enable PKCE
)

@app.route('/login')
def login():
redirect_uri = 'http://localhost:5000/callback'
return oauth.provider.authorize_redirect(redirect_uri)

@app.route('/callback')
def callback():
token = oauth.provider.authorize_access_token()

# Create HTTP client with OAuth headers
http_client = httpx.Client(headers={
'Authorization': f"Bearer {token['access_token']}",
'X-Glean-Auth-Type': 'OAUTH',
})

# Use OAuth token with Glean
with Glean(
instance=os.getenv('GLEAN_INSTANCE'),
client=http_client,
) as glean:
results = glean.client.search.query(
search_request=models.SearchRequest(
query='quarterly reports',
page_size=10,
)
)

return jsonify(results.to_dict())

if __name__ == '__main__':
app.run(port=5000)
tip

Access tokens typically expire after ~1 hour. For production use, implement token refresh using token['refresh_token'].

Error Handling

from glean.api_client.exceptions import GleanAPIError

try:
response = client.client.chat.create(messages=[...])
except GleanAPIError as e:
print(f"API error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")

Testing

Unit Testing with Mocks

import pytest
from unittest.mock import patch, MagicMock

@pytest.fixture
def mock_glean_client():
with patch('your_app.Glean') as mock:
client_instance = MagicMock()
mock.return_value.__enter__.return_value = client_instance
yield client_instance

def test_chat_service(mock_glean_client):
mock_response = MagicMock()
mock_response.text = "Test response"
mock_glean_client.client.chat.create.return_value = mock_response

result = send_message("Hello")
assert result == "Test response"

Additional Resources