The Glean Python SDK provides convenient access to the Glean REST API from any Python 3.8+ application. It includes type hints for all request parameters and response fields, and supports both synchronous and asynchronous usage via httpx.
This SDK combines both the Client and Indexing API namespaces into a single unified package:
- Client API: Used for search, retrieval, and end-user interactions with Glean content
- Indexing API: Used for indexing content, permissions, and other administrative operations
Each namespace has its own authentication requirements and access patterns. While they serve different purposes, having them in a single SDK provides a consistent developer experience across all Glean API interactions.
# Example of accessing Client namespacefromglean.api_clientimportGleanimportoswithGlean(api_token="client-token", server_url="https://mycompany-be.glean.com") asglean:
search_response=glean.client.search.query(query="search term")
print(search_response)
# Example of accessing Indexing namespace fromglean.api_clientimportGlean, modelsimportoswithGlean(api_token="indexing-token", server_url="https://mycompany-be.glean.com") asglean:
document_response=glean.indexing.documents.index(
document=models.Document(
id="doc-123",
title="Sample Document",
container_id="container-456",
datasource="confluence"
)
)Remember that each namespace requires its own authentication token type as described in the Authentication Methods section.
Note
Python version upgrade policy
Once a Python version reaches its official end of life date, a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.
The SDK can be installed with either pip or poetry package managers.
PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install glean-api-clientPoetry is a modern tool that simplifies dependency management and package publishing by using a single pyproject.toml file to handle project metadata and dependencies.
poetry add glean-api-clientYou can use this SDK in a Python shell with uv and the uvx command that comes with it like so:
uvx --from glean-api-client pythonIt's also possible to write a standalone Python script without needing to set up a whole project like so:
#!/usr/bin/env -S uv run --script# /// script# requires-python = ">=3.9"# dependencies = [# "glean-api-client",# ]# ///fromglean.api_clientimportGleansdk=Glean(
# SDK arguments
)
# Rest of script here...Once that is saved to a file, you can run it with uv run script.py where
script.py can be replaced with the actual file name.
Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.
# Synchronous Examplefromglean.api_clientimportGlean, modelsimportoswithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.client.chat.create(messages=[
{
"fragments": [
models.ChatMessageFragment(
text="What are the company holidays this year?",
),
],
},
], timeout_millis=30000)
# Handle responseprint(res)The same SDK client can also be used to make asynchronous requests by importing asyncio.
# Asynchronous Exampleimportasynciofromglean.api_clientimportGlean, modelsimportosasyncdefmain():
asyncwithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=awaitglean.client.chat.create_async(messages=[
{
"fragments": [
models.ChatMessageFragment(
text="What are the company holidays this year?",
),
],
},
], timeout_millis=30000)
# Handle responseprint(res)
asyncio.run(main())# Synchronous Examplefromglean.api_clientimportGlean, modelsimportoswithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.client.chat.create_stream(messages=[
{
"fragments": [
models.ChatMessageFragment(
text="What are the company holidays this year?",
),
],
},
], timeout_millis=30000)
# Handle responseprint(res)The same SDK client can also be used to make asynchronous requests by importing asyncio.
# Asynchronous Exampleimportasynciofromglean.api_clientimportGlean, modelsimportosasyncdefmain():
asyncwithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=awaitglean.client.chat.create_stream_async(messages=[
{
"fragments": [
models.ChatMessageFragment(
text="What are the company holidays this year?",
),
],
},
], timeout_millis=30000)
# Handle responseprint(res)
asyncio.run(main())This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
|---|---|---|---|
api_token | http | HTTP Bearer | GLEAN_API_TOKEN |
To authenticate with the API the api_token parameter must be set when initializing the SDK client instance. For example:
fromglean.api_clientimportGleanimportoswithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.agents.search(name="HR Policy Agent")
# Handle responseprint(res)Glean supports different authentication methods depending on which API namespace you're using:
The Client namespace supports two authentication methods:
Manually Provisioned API Tokens
- Can be created by an Admin or a user with the API Token Creator role
- Used for server-to-server integrations
OAuth
- Requires OAuth setup to be completed by an Admin
- Used for user-based authentication flows
The Indexing namespace supports only one authentication method:
- Manually Provisioned API Tokens
- Can be created by an Admin or a user with the API Token Creator role
- Used for secure document indexing operations
Important
Client tokens will not work for Indexing operations, and Indexing tokens will not work for Client operations. You must use the appropriate token type for the namespace you're accessing.
For more information on obtaining the appropriate token type, please contact your Glean administrator.
Available methods
- search - Search agents
- get - Get agent
- get_schemas - Get agent schemas
- create_run - Create agent run
- create - Create a chat response
- create - Create an agent
- retrieve - Retrieve an agent
- update - Edit an agent
- retrieve_schemas - List an agent's schemas
- import_ - Import an agent
- list - Search agents
- run_stream - Create an agent run and stream the response
- run - Create an agent run and wait for the response
- create - Create Answer
- delete - Delete Answer
- update - Update Answer
- retrieve - Read Answer
list- List Answers⚠️ Deprecated
- check_datasource_auth - Check datasource authorization
- create_token - Create authentication token
- create - Chat
- delete_all - Deletes all saved Chats owned by a user
- delete - Deletes saved Chats
- retrieve - Retrieves a Chat
- list - Retrieves all saved Chats
- retrieve_application - Gets the metadata for a custom Chat application
- upload_files - Upload files for Chat
- retrieve_files - Get files uploaded by a user for Chat
- delete_files - Delete files uploaded by a user for chat
- retrieve_file - Download a chat file
- create_stream - Chat
- add_items - Add Collection item
- create - Create Collection
- delete - Delete Collection
- delete_item - Delete Collection item
- update - Update Collection
- update_item - Update Collection item
- retrieve - Read Collection
- list - List Collections
- retrieve_configuration - Get datasource instance configuration
- update_configuration - Update datasource instance configuration
- retrieve_credential_status - Get datasource instance credential status
- rotate_credentials - Rotate datasource instance credentials
- retrieve_permissions - Read document permissions
- retrieve - Read documents
- retrieve_by_facets - Read documents by facets
- summarize - Summarize documents
- list - List entities
- read_people - Read people
- retrieve_person_photo - Get person photo
- create - Creates findings export
- list - Lists findings exports
- download - Downloads findings export
- delete - Deletes findings export
- retrieve - Gets specified policy
- update - Updates an existing policy
- list - Lists policies
- create - Creates new policy
- download - Downloads violations CSV for policy
- create - Creates new one-time report
- download - Downloads violations CSV for report
- status - Fetches report run status
- retrieve - Get insights
- retrieve - Read messages
- query_as_admin - Search the index (admin)
- autocomplete - Autocomplete
- retrieve_feed - Feed of documents and events
- recommendations - Recommend documents
- query - Search
- create - Create shortcut
- delete - Delete shortcut
- retrieve - Read shortcut
- list - List shortcuts
- update - Update shortcut
- list - List available tools
- run - Execute the specified tool
- retrieve_action_pack_auth_status - Get end-user authentication status for an action pack.
- authorize_action_pack - Start the OAuth authorization flow for an action pack.
- retrieve_tool_server_auth_status - Get end-user authentication status for a tool server.
- authorize_tool_server - Start the OAuth authorization flow for a tool server.
- get_tool_server_tools - Get tool definitions from a tool server.
- add_reminder - Create verification
- list - List verifications
- verify - Update verification
- rotate_token - Rotate token
- upsert - Add or update custom metadata
- delete - Remove custom metadata
- get_schema - Retrieve metadata schema
- upsert_schema - Create or update metadata schema
- delete_schema - Remove metadata schema
- status - Beta: Get datasource status
- add - Add or update datasource
- retrieve_config - Get datasource config
- submit - Submit datasource data
add_or_update - Index document
index - Index documents
bulk_index - Bulk index documents
process_all - Schedules the processing of uploaded documents
delete - Delete document
debug - Beta: Get document information
debug_many - Beta: Get information of a batch of documents
check_access - Check document access
status- Get document upload and indexing status⚠️ Deprecatedcount- Get document count⚠️ Deprecateddebug_events - Beta: Get document lifecycle events
debug - Beta: Get user information
count- Get user count⚠️ Deprecatedindex - Index employee
bulk_index- Bulk index employees⚠️ Deprecatedprocess_all_employees_and_teams - Schedules the processing of uploaded employees and teams
delete - Delete employee
index_team - Index team
delete_team - Delete team
bulk_index_teams - Bulk index teams
- update_permissions - Update document permissions
- index_user - Index user
- bulk_index_users - Bulk index users
- index_group - Index group
- bulk_index_groups - Bulk index groups
- index_membership - Index membership
- bulk_index_memberships - Bulk index memberships for a group
- process_memberships - Schedules the processing of group memberships
- delete_user - Delete user
- delete_group - Delete group
- delete_membership - Delete membership
- authorize_beta_users - Beta users
- bulk_index - Bulk index external shortcuts
- upload - Upload shortcuts
- query - Search
- list_filters - List search filters
- create - Create skill
- list - List skills
- validate - Validate skill bundle
- import_ - Import skills from GitHub
- preview_source - Preview a GitHub skill source
- update - Update skill
- delete - Delete skill
- retrieve - Retrieve skill
- retrieve_content - Download skill content
- sync - Sync a GitHub-imported skill
- create_version - Create skill version
- list_versions - List skill versions
- retrieve_version - Retrieve skill version
- retrieve_version_content - Download skill version content
Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
Tip
For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.
fromglean.api_clientimportGleanimportoswithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.skills.create(file={
"file_name": "example.file",
"content": open("example.file", "rb"),
})
# Handle responseprint(res)Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:
fromglean.api_clientimportGleanfromglean.api_client.utilsimportBackoffStrategy, RetryConfigimportoswithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.agents.search(name="HR Policy Agent",
RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))
# Handle responseprint(res)If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:
fromglean.api_clientimportGleanfromglean.api_client.utilsimportBackoffStrategy, RetryConfigimportoswithGlean(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.agents.search(name="HR Policy Agent")
# Handle responseprint(res)All operations return a response object or raise an exception:
| Status Code | Description | Error Type | Content Type |
|---|---|---|---|
| 400 | Invalid Request | errors.GleanError | */* |
| 401 | Not Authorized | errors.GleanError | */* |
| 403 | Permission Denied | errors.GleanDataError | application/json |
| 408 | Request Timeout | errors.GleanError | */* |
| 422 | Invalid Query | errors.GleanDataError | application/json |
| 429 | Too Many Requests | errors.GleanError | */* |
| 4XX | Other Client Errors | errors.GleanError | */* |
| 5XX | Internal Server Errors | errors.GleanError | */* |
fromglean.api_clientimportGlean, errors, modelsimportoswithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asg_client:
try:
res=g_client.client.search.execute(search_request=models.SearchRequest(
tracking_token="trackingToken",
page_size=10,
query="vacation policy",
request_options=models.SearchRequestOptions(
facet_filters=[
models.FacetFilter(
field_name="type",
values=[
models.FacetFilterValue(
value="article",
relation_type=models.RelationType.EQUALS,
),
models.FacetFilterValue(
value="document",
relation_type=models.RelationType.EQUALS,
),
],
),
models.FacetFilter(
field_name="department",
values=[
models.FacetFilterValue(
value="engineering",
relation_type=models.RelationType.EQUALS,
),
],
),
],
facet_bucket_size=246815,
),
))
# Handle responseprint(res)
excepterrors.GleanErrorase:
print(e.message)
print(e.status_code)
print(e.raw_response)
print(e.body)
# If the server returned structured dataexcepterrors.GleanDataErrorase:
print(e.data)
print(e.data.errorMessage)By default, an API error will raise a errors.GleanError exception, which has the following properties:
| Property | Type | Description |
|---|---|---|
error.status_code | int | The HTTP status code |
error.message | str | The error message |
error.raw_response | httpx.Response | The raw HTTP response |
error.body | str | The response content |
The default server https://{instance}-be.glean.com contains variables and is set to https://instance-name-be.glean.com by default. To override default values, the following parameters are available when initializing the SDK client instance:
| Variable | Parameter | Default | Description |
|---|---|---|---|
instance | instance: str | "instance-name" | The instance name (typically the email domain without the TLD) that determines the deployment backend. |
fromglean.api_clientimportGleanimportoswithGlean(
server_idx=0,
instance="instance-name",
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.agents.search(name="HR Policy Agent")
# Handle responseprint(res)The default server can be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:
fromglean.api_clientimportGleanimportoswithGlean(
server_url="https://instance-name-be.glean.com",
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.agents.search(name="HR Policy Agent")
# Handle responseprint(res)The server URL can also be overridden on a per-operation basis, provided a server list was specified for the operation. For example:
fromglean.api_clientimportGleanimportoswithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
res=glean.indexing.datasources.submit(datasource_instance="<value>", type_="<value>", request_body={
"key": "<value>",
"key1": "<value>",
"key2": "<value>",
}, server_url="https://instance-name-be.glean.com")
# Handle responseprint(res)The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance.
Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls.
This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.
For example, you could specify a header for every request that this sdk makes as follows:
fromglean.api_clientimportGleanimporthttpxhttp_client=httpx.Client(headers={"x-custom-header": "someValue"})
s=Glean(client=http_client)or you could wrap the client with your own custom logic:
fromglean.api_clientimportGleanfromglean.api_client.httpclientimportAsyncHttpClientimporthttpxclassCustomClient(AsyncHttpClient):
client: AsyncHttpClientdef__init__(self, client: AsyncHttpClient):
self.client=clientasyncdefsend(
self,
request: httpx.Request,
*,
stream: bool=False,
auth: Union[
httpx._types.AuthTypes, httpx._client.UseClientDefault, None
] =httpx.USE_CLIENT_DEFAULT,
follow_redirects: Union[
bool, httpx._client.UseClientDefault
] =httpx.USE_CLIENT_DEFAULT,
) ->httpx.Response:
request.headers["Client-Level-Header"] ="added by client"returnawaitself.client.send(
request, stream=stream, auth=auth, follow_redirects=follow_redirects
)
defbuild_request(
self,
method: str,
url: httpx._types.URLTypes,
*,
content: Optional[httpx._types.RequestContent] =None,
data: Optional[httpx._types.RequestData] =None,
files: Optional[httpx._types.RequestFiles] =None,
json: Optional[Any] =None,
params: Optional[httpx._types.QueryParamTypes] =None,
headers: Optional[httpx._types.HeaderTypes] =None,
cookies: Optional[httpx._types.CookieTypes] =None,
timeout: Union[
httpx._types.TimeoutTypes, httpx._client.UseClientDefault
] =httpx.USE_CLIENT_DEFAULT,
extensions: Optional[httpx._types.RequestExtensions] =None,
) ->httpx.Request:
returnself.client.build_request(
method,
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
s=Glean(async_client=CustomClient(httpx.AsyncClient()))The Glean class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.
fromglean.api_clientimportGleanimportosdefmain():
withGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
# Rest of application here...# Or when using async:asyncdefamain():
asyncwithGlean(
api_token=os.getenv("GLEAN_API_TOKEN", ""),
) asglean:
# Rest of application here...You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass your own logger class directly into your SDK.
fromglean.api_clientimportGleanimportlogginglogging.basicConfig(level=logging.DEBUG)
s=Glean(debug_logger=logging.getLogger("glean.api_client"))You can also enable a default debug logger by setting an environment variable GLEAN_DEBUG to true.
The SDK provides options to test upcoming API changes before they become the default behavior. This is useful for:
- Testing experimental features before they are generally available
- Preparing for deprecations by excluding deprecated endpoints ahead of their removal
You can configure these options either via environment variables or SDK constructor options:
importos# Set environment variables before initializing the SDKos.environ["X_GLEAN_EXCLUDE_DEPRECATED_AFTER"] ="2026-10-15"os.environ["X_GLEAN_INCLUDE_EXPERIMENTAL"] ="true"fromglean.api_clientimportGleanglean=Glean(
api_token=os.environ.get("GLEAN_API_TOKEN", ""),
server_url="https://mycompany-be.glean.com",
)importosfromglean.api_clientimportGleanglean=Glean(
api_token=os.environ.get("GLEAN_API_TOKEN", ""),
server_url="https://mycompany-be.glean.com",
exclude_deprecated_after="2026-10-15",
include_experimental=True,
)| Option | Environment Variable | Type | Description |
|---|---|---|---|
exclude_deprecated_after | X_GLEAN_EXCLUDE_DEPRECATED_AFTER | str (date) | Exclude API endpoints that will be deprecated after this date (format: YYYY-MM-DD). Use this to test your integration against upcoming deprecations. |
include_experimental | X_GLEAN_INCLUDE_EXPERIMENTAL | bool | When True, enables experimental API features that are not yet generally available. Use this to preview and test new functionality. |
Note
Environment variables take precedence over SDK constructor options when both are set.
Warning
Experimental features may change or be removed without notice. Do not rely on experimental features in production environments.
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.