GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - gleanwork/api-client-java: The official Java library for the Glean API

BranchesTags
Open more actions menu

Latest commit

 

History

330 Commits
330 Commits

Folders and files

NameName
Last commit message
Last commit date
.github
.github
 
 
.speakeasy
.speakeasy
 
 
docs
docs
 
 
examples
examples
 
 
gradle/wrapper
gradle/wrapper
 
 
src
src
 
 
tests/mockserver/testdata
tests/mockserver/testdata
 
 
.gitattributes
.gitattributes
 
 
.gitignore
.gitignore
 
 
CONTRIBUTING.md
CONTRIBUTING.md
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
RELEASES.md
RELEASES.md
 
 
USAGE.md
USAGE.md
 
 
build-extras.gradle
build-extras.gradle
 
 
build.gradle
build.gradle
 
 
gradle.properties
gradle.properties
 
 
gradlew
gradlew
 
 
gradlew.bat
gradlew.bat
 
 
mise.toml
mise.toml
 
 
publishing.gradle
publishing.gradle
 
 
settings.gradle
settings.gradle
 
 

Repository files navigation

api-client-java

The Glean Java SDK provides convenient access to the Glean REST API for Java 8+. It includes POJOs for all API models, fluent builders for requests, and supports both synchronous and asynchronous execution using standard HTTP clients.

Unified SDK Architecture

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 namespace
Glean glean = Glean.builder()
        .apiToken("client-token")
        .serverURL("https://mycompany-be.glean.com")
        .build();
glean.client().search().query()
        .searchRequest(SearchRequest.builder().query("search term").build())
        .call();

// Example of accessing Indexing namespace
Glean glean = Glean.builder()
        .apiToken("indexing-token")
        .serverURL("https://mycompany-be.glean.com")
        .build();
glean.indexing().documents().index()
        .request(DocumentBulkIndexRequest.builder() /* document data */ .build())
        .call();

Remember that each namespace requires its own authentication token type as described in the Authentication Methods section.

Table of Contents

  • api-client-java
    • Unified SDK Architecture
    • SDK Installation
    • SDK Example Usage
    • Asynchronous Support
    • Authentication
    • Available Resources and Operations
    • Server-sent event streaming
    • Error Handling
    • Server Selection
    • Custom HTTP Client
    • Debugging
    • Experimental Features and Deprecation Testing
    • Jackson Configuration
  • Development
    • Maturity
    • Contributions

SDK Installation

Getting started

JDK 11 or later is required.

The samples below show how a published SDK artifact is used:

Gradle:

implementation 'com.glean.api-client:glean-api-client:0.17.22'

Maven:

<dependency>
    <groupId>com.glean.api-client</groupId>
    <artifactId>glean-api-client</artifactId>
    <version>0.17.22</version>
</dependency>

How to build

After cloning the git repository to your file system you can build the SDK artifact from source to the build directory by running ./gradlew build on *nix systems or gradlew.bat on Windows systems.

If you wish to build from source and publish the SDK artifact to your local Maven repository (on your filesystem) then use the following command (after cloning the git repo locally):

On *nix:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

SDK Example Usage

Example 1

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.ChatResponse;
import java.lang.Exception;
import java.util.List;

public class Application {

    public static void main(String[] args) throws Exception {

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        ChatResponse res = sdk.client().chat().create()
                .chatRequest(ChatRequest.builder()
                    .messages(List.of(
                        ChatMessage.builder()
                            .fragments(List.of(
                                ChatMessageFragment.builder()
                                    .text("What are the company holidays this year?")
                                    .build()))
                            .build()))
                    .build())
                .call();

        if (res.chatResponse().isPresent()) {
            System.out.println(res.chatResponse().get());
        }
    }
}

Example 2

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.ChatStreamResponse;
import java.lang.Exception;
import java.util.List;

public class Application {

    public static void main(String[] args) throws Exception {

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        ChatStreamResponse res = sdk.client().chat().createStream()
                .chatRequest(ChatRequest.builder()
                    .messages(List.of(
                        ChatMessage.builder()
                            .fragments(List.of(
                                ChatMessageFragment.builder()
                                    .text("What are the company holidays this year?")
                                    .build()))
                            .build()))
                    .build())
                .call();

        if (res.chatRequestStream().isPresent()) {
            System.out.println(res.chatRequestStream().get());
        }
    }
}

Asynchronous Call

An asynchronous SDK client is also available that returns a CompletableFuture<T>. See Asynchronous Support for more details on async benefits and reactive library integration.

package hello.world;

import com.glean.api_client.glean_api_client.AsyncGlean;
import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.PlatformAgentsSearchRequest;
import com.glean.api_client.glean_api_client.models.operations.async.PlatformAgentsSearchResponse;
import java.util.concurrent.CompletableFuture;

public class Application {

    public static void main(String[] args) {

        AsyncGlean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build()
            .async();

        PlatformAgentsSearchRequest req = PlatformAgentsSearchRequest.builder()
                .name("HR Policy Agent")
                .build();

        CompletableFuture<PlatformAgentsSearchResponse> resFut = sdk.agents().search()
                .request(req)
                .call();

        resFut.thenAccept(res -> {
            if (res.platformAgentsSearchResponse().isPresent()) {
                System.out.println(res.platformAgentsSearchResponse().get());
            }
        });
    }
}

Union Consumption Patterns

When a response field is a union model:

  • Discriminated unions: branch on the discriminator (switch) and then narrow to the concrete type.
  • Non-discriminated unions: use generated accessors (for example string(), asLong(), simpleObject()) to determine the active variant.

For full model-specific examples (including Java 11/16/21 variants), see each union model's Supported Types section in the generated model docs.

Asynchronous Support

The SDK provides comprehensive asynchronous support using Java's CompletableFuture<T> and Reactive Streams Publisher<T> APIs. This design makes no assumptions about your choice of reactive toolkit, allowing seamless integration with any reactive library.

Why Use Async?

Asynchronous operations provide several key benefits:

  • Non-blocking I/O: Your threads stay free for other work while operations are in flight
  • Better resource utilization: Handle more concurrent operations with fewer threads
  • Improved scalability: Build highly responsive applications that can handle thousands of concurrent requests
  • Reactive integration: Works seamlessly with reactive streams and backpressure handling
Reactive Library Integration

The SDK returns Reactive Streams Publisher<T> instances for operations dealing with streams involving multiple I/O interactions. We use Reactive Streams instead of JDK Flow API to provide broader compatibility with the reactive ecosystem, as most reactive libraries natively support Reactive Streams.

Why Reactive Streams over JDK Flow?

  • Broader ecosystem compatibility: Most reactive libraries (Project Reactor, RxJava, Akka Streams, etc.) natively support Reactive Streams
  • Industry standard: Reactive Streams is the de facto standard for reactive programming in Java
  • Better interoperability: Seamless integration without additional adapters for most use cases

Integration with Popular Libraries:

  • Project Reactor: Use Flux.from(publisher) to convert to Reactor types
  • RxJava: Use Flowable.fromPublisher(publisher) for RxJava integration
  • Akka Streams: Use Source.fromPublisher(publisher) for Akka Streams integration
  • Vert.x: Use ReadStream.fromPublisher(vertx, publisher) for Vert.x reactive streams
  • Mutiny: Use Multi.createFrom().publisher(publisher) for Quarkus Mutiny integration

For JDK Flow API Integration: If you need JDK Flow API compatibility (e.g., for Quarkus/Mutiny 2), you can use adapters:

// Convert Reactive Streams Publisher to Flow Publisher
Flow.Publisher<T> flowPublisher = FlowAdapters.toFlowPublisher(reactiveStreamsPublisher);

// Convert Flow Publisher to Reactive Streams Publisher
Publisher<T> reactiveStreamsPublisher = FlowAdapters.toPublisher(flowPublisher);

For standard single-response operations, the SDK returns CompletableFuture<T> for straightforward async execution.

Supported Operations

Async support is available for:

  • Server-sent Events: Stream real-time events with Reactive Streams Publisher<T>
  • JSONL Streaming: Process streaming JSON lines asynchronously
  • Pagination: Iterate through paginated results using callAsPublisher() and callAsPublisherUnwrapped()
  • File Uploads: Upload files asynchronously with progress tracking
  • File Downloads: Download files asynchronously with streaming support
  • Standard Operations: All regular API calls return CompletableFuture<T> for async execution

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme Environment Variable
apiToken http HTTP Bearer GLEAN_API_TOKEN

To authenticate with the API the apiToken parameter must be set when initializing the SDK client instance. For example:

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.PlatformAgentsSearchRequest;
import com.glean.api_client.glean_api_client.models.errors.PlatformProblemDetailException;
import com.glean.api_client.glean_api_client.models.operations.PlatformAgentsSearchResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws PlatformProblemDetailException, Exception {

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        PlatformAgentsSearchRequest req = PlatformAgentsSearchRequest.builder()
                .name("HR Policy Agent")
                .build();

        PlatformAgentsSearchResponse res = sdk.agents().search()
                .request(req)
                .call();

        if (res.platformAgentsSearchResponse().isPresent()) {
            System.out.println(res.platformAgentsSearchResponse().get());
        }
    }
}

Authentication Methods

Glean supports different authentication methods depending on which API namespace you're using:

Client Namespace

The Client namespace supports two authentication methods:

  1. 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
  2. OAuth

    • Requires OAuth setup to be completed by an Admin
    • Used for user-based authentication flows

Indexing Namespace

The Indexing namespace supports only one authentication method:

  1. 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 Resources and Operations

Available methods

Admin.Agents

  • list - List all agents

Admin.Idpgroups

  • list - List IdP groups
  • get - Get an IdP group

Admin.Oauth.Clients

  • list - List OAuth clients
  • get - Get an OAuth client

Agents

  • search - Search agents
  • get - Get agent
  • getSchemas - Get agent schemas
  • createRun - Create agent run
  • getRun - Get agent run
  • cancelRun - Cancel an agent run
  • respondToRun - Respond to agent run approvals

Chat

  • create - Create a chat response
  • update - Update a chat
  • createStream - Create a streaming chat response

Client.Activity

  • report - Report document activity
  • feedback - Report client activity

Client.Agents

  • create - Create an agent
  • retrieve - Retrieve an agent ⚠️ Deprecated
  • update - Edit an agent
  • retrieveSchemas - List an agent's schemas ⚠️ Deprecated
  • import_ - Import an agent
  • list - Search agents ⚠️ Deprecated
  • runStream - Create an agent run and stream the response ⚠️ Deprecated
  • run - Create an agent run and wait for the response ⚠️ Deprecated

Client.Announcements

  • create - Create Announcement
  • delete - Delete Announcement
  • update - Update Announcement

Client.Answers

  • create - Create Answer
  • delete - Delete Answer
  • update - Update Answer
  • retrieve - Read Answer
  • list - List Answers ⚠️ Deprecated

Client.Authentication

  • checkDatasourceAuth - Check datasource authorization
  • createToken - Create authentication token

Client.Chat

  • create - Chat
  • deleteAll - Deletes all saved Chats owned by a user
  • delete - Deletes saved Chats
  • retrieve - Retrieves a Chat
  • list - Retrieves all saved Chats
  • retrieveApplication - Gets the metadata for a custom Chat application
  • uploadFiles - Upload files for Chat
  • retrieveFiles - Get files uploaded by a user for Chat
  • deleteFiles - Delete files uploaded by a user for chat
  • retrieveFile - Download a chat file
  • createStream - Chat

Client.Collections

  • addItems - Add Collection item
  • create - Create Collection
  • delete - Delete Collection
  • deleteItem - Delete Collection item
  • update - Update Collection
  • updateItem - Update Collection item
  • retrieve - Read Collection
  • list - List Collections

Client.Datasources

  • retrieveConfiguration - Get datasource instance configuration
  • updateConfiguration - Update datasource instance configuration
  • retrieveCredentialStatus - Get datasource instance credential status
  • rotateCredentials - Rotate datasource instance credentials

Client.Documents

  • retrievePermissions - Read document permissions
  • retrieve - Read documents
  • retrieveByFacets - Read documents by facets
  • summarize - Summarize documents

Client.Entities

  • list - List entities
  • readPeople - Read people
  • retrievePersonPhoto - Get person photo

Client.Governance.Data.Findings

  • create - Creates findings export
  • list - Lists findings exports
  • download - Downloads findings export
  • delete - Deletes findings export

Client.Governance.Data.Policies

  • retrieve - Gets specified policy
  • update - Updates an existing policy
  • list - Lists policies
  • create - Creates new policy
  • download - Downloads violations CSV for policy

Client.Governance.Data.Reports

  • create - Creates new one-time report
  • download - Downloads violations CSV for report
  • status - Fetches report run status

Client.Governance.Documents.Visibilityoverrides

  • list - Fetches documents visibility
  • create - Hide or unhide docs

Client.Insights

  • retrieve - Get insights

Client.Messages

  • retrieve - Read messages

Client.Pins

  • update - Update pin
  • retrieve - Read pin
  • list - List pins
  • create - Create pin
  • remove - Delete pin

Client.Search

  • queryAsAdmin - Search the index (admin)
  • autocomplete - Autocomplete
  • retrieveFeed - Feed of documents and events
  • recommendations - Recommend documents
  • query - Search

Client.Shortcuts

  • create - Create shortcut
  • delete - Delete shortcut
  • retrieve - Read shortcut
  • list - List shortcuts
  • update - Update shortcut

Client.Tools

  • list - List available tools
  • run - Execute the specified tool
  • retrieveActionPackAuthStatus - Get end-user authentication status for an action pack.
  • authorizeActionPack - Start the OAuth authorization flow for an action pack.
  • retrieveToolServerAuthStatus - Get end-user authentication status for a tool server.
  • authorizeToolServer - Start the OAuth authorization flow for a tool server.
  • getToolServerTools - Get tool definitions from a tool server.

Client.Verification

  • addReminder - Create verification
  • list - List verifications
  • verify - Update verification

Departments

  • list - List departments
  • get - Get a department

Documents

  • getByUrl - Get document by URL
  • getById - Get document by ID
  • batch - Batch get documents

Indexing.Authentication

  • rotateToken - Rotate token

Indexing.CustomMetadata

  • upsert - Add or update custom metadata
  • delete - Remove custom metadata
  • getSchema - Retrieve metadata schema
  • upsertSchema - Create or update metadata schema
  • deleteSchema - Remove metadata schema

Indexing.Datasource

  • status - Beta: Get datasource status

Indexing.Datasources

  • add - Add or update datasource
  • retrieveConfig - Get datasource config
  • submit - Submit datasource data

Indexing.Documents

  • addOrUpdate - Index document

  • index - Index documents

  • bulkIndex - Bulk index documents

  • processAll - Schedules the processing of uploaded documents

  • delete - Delete document

  • debug - Beta: Get document information

  • debugMany - Beta: Get information of a batch of documents

  • checkAccess - Check document access

  • status - Get document upload and indexing status ⚠️ Deprecated

  • count - Get document count ⚠️ Deprecated

  • debugEvents - Beta: Get document lifecycle events

Indexing.People

  • debug - Beta: Get user information

  • count - Get user count ⚠️ Deprecated

  • index - Index employee

  • bulkIndex - Bulk index employees ⚠️ Deprecated

  • processAllEmployeesAndTeams - Schedules the processing of uploaded employees and teams

  • delete - Delete employee

  • indexTeam - Index team

  • deleteTeam - Delete team

  • bulkIndexTeams - Bulk index teams

Indexing.Permissions

  • updatePermissions - Update document permissions
  • indexUser - Index user
  • bulkIndexUsers - Bulk index users
  • indexGroup - Index group
  • bulkIndexGroups - Bulk index groups
  • indexMembership - Index membership
  • bulkIndexMemberships - Bulk index memberships for a group
  • processMemberships - Schedules the processing of group memberships
  • deleteUser - Delete user
  • deleteGroup - Delete group
  • deleteMembership - Delete membership
  • authorizeBetaUsers - Beta users

Indexing.Shortcuts

  • bulkIndex - Bulk index external shortcuts
  • upload - Upload shortcuts

Search

  • query - Search
  • listFilters - List search filters

Skills

  • create - Create skill
  • list - List skills
  • import_ - Import skills from GitHub
  • validate - Validate skill bundle
  • previewSource - Preview a GitHub skill source
  • update - Update skill
  • delete - Delete skill
  • retrieve - Retrieve skill
  • retrieveContent - Download skill content
  • sync - Sync a GitHub-imported skill
  • createVersion - Create skill version
  • listVersions - List skill versions
  • retrieveVersion - Retrieve skill version
  • retrieveVersionContent - Download skill version content
  • previewSourceStream - Preview a GitHub skill source as events

Triggers

  • create - Create trigger
  • list - List triggers
  • get - Get trigger
  • update - Update trigger
  • delete - Delete trigger
  • searchEvents - Search events for a trigger
  • listPresets - List trigger presets
  • getPreset - Get trigger preset
  • listPresetInputValues - Search trigger preset input values
  • searchPresetEvents - Search events for a trigger preset

Users

  • list - List users
  • get - Get user

Server-sent event streaming

Server-sent events are used to stream content from certain operations. These operations will expose the stream as an iterable that can be consumed using a simple for loop. The loop will terminate when the server no longer has any events to send and closes the underlying connection.

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.errors.PlatformProblemDetailException;
import com.glean.api_client.glean_api_client.models.operations.*;
import com.glean.api_client.glean_api_client.utils.EventStream;
import java.lang.Exception;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class Application {

    public static void main(String[] args) throws PlatformProblemDetailException, Exception {

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        PlatformChatCreateStreamRequest req = PlatformChatCreateStreamRequest.builder()
                .input(PlatformChatCreateStreamInput.of("Summarize our parental leave policy as JSON."))
                .text(PlatformChatCreateStreamText.builder()
                    .format(PlatformChatCreateStreamFormat.of(PlatformChatJsonSchemaFormat.builder()
                        .type(PlatformChatJsonSchemaFormatType.JSON_SCHEMA)
                        .name("policy_summary")
                        .schema(Map.ofEntries(
                            Map.entry("type", "object"),
                            Map.entry("properties", Map.ofEntries(
                                Map.entry("eligible_employees", Map.ofEntries(
                                    Map.entry("type", "string"))),
                                Map.entry("duration_weeks", Map.ofEntries(
                                    Map.entry("type", "integer"))))),
                            Map.entry("required", List.of(
                                "eligible_employees",
                                "duration_weeks"))))
                        .build()))
                    .build())
                .build();

        PlatformChatCreateStreamResponse res = sdk.chat().createStream()
                .request(req)
                .call();

        // handle event stream, must be closed after use!
        try (EventStream<PlatformChatStreamEventServerSentEvent> events = res.events()) {
            // Option 1: Use for-each loop
            for (PlatformChatStreamEventServerSentEvent event : events) {
                System.out.println(event);
            }

            // Option 2: Use Stream API
            try (Stream<PlatformChatStreamEventServerSentEvent> stream = events.stream()) {
                 stream.forEach(System.out::println);
            }
        }
    }
}

Reactive Streams Interoperability

An asynchronous SDK client is also available for event streaming that returns a Flow.Publisher<T>. See Asynchronous Support for more details on async benefits and reactive library integration.

package hello.world;

import com.glean.api_client.glean_api_client.AsyncGlean;
import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.*;
import com.glean.api_client.glean_api_client.models.operations.async.PlatformChatCreateStreamResponse;
import com.glean.api_client.glean_api_client.utils.reactive.EventStream;
import java.util.List;
import java.util.Map;
import reactor.core.publisher.Flux;

public class Application {

    public static void main(String[] args) {

        AsyncGlean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build()
            .async();

        PlatformChatCreateStreamRequest req = PlatformChatCreateStreamRequest.builder()
                .input(PlatformChatCreateStreamInput.of("Summarize our parental leave policy as JSON."))
                .text(PlatformChatCreateStreamText.builder()
                    .format(PlatformChatCreateStreamFormat.of(PlatformChatJsonSchemaFormat.builder()
                        .type(PlatformChatJsonSchemaFormatType.JSON_SCHEMA)
                        .name("policy_summary")
                        .schema(Map.ofEntries(
                            Map.entry("type", "object"),
                            Map.entry("properties", Map.ofEntries(
                                Map.entry("eligible_employees", Map.ofEntries(
                                    Map.entry("type", "string"))),
                                Map.entry("duration_weeks", Map.ofEntries(
                                    Map.entry("type", "integer"))))),
                            Map.entry("required", List.of(
                                "eligible_employees",
                                "duration_weeks"))))
                        .build()))
                    .build())
                .build();

        EventStream<PlatformChatCreateStreamResponse, PlatformChatStreamEventServerSentEvent> res = sdk.chat().createStream()
                .request(req)
                .call();

        // handle async event stream using Reactive Streams Publisher
        // EventStream is a Reactive Streams Publisher, providing broad compatibility with reactive libraries

        // Example using Project Reactor (illustrative)
        Flux<PlatformChatStreamEventServerSentEvent>  flux = Flux.from(res);
        flux.subscribe(
            event -> System.out.println(event),
            error -> error.printStackTrace(),
            () -> System.out.println("Event stream completed")
        );
    }
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.

GleanError is the base class for all HTTP error responses. It has the following properties:

Method Type Description
message() String Error message
code() int HTTP response status code eg 404
headers Map<String, List<String>> HTTP response headers
body() byte[] HTTP body as a byte array. Can be empty array if no body is returned.
bodyAsString() String HTTP body as a UTF-8 string. Can be empty string if no body is returned.
rawResponse() HttpResponse<?> Raw HTTP response (body already read and not available for re-read)

Example

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.PlatformAgentsSearchRequest;
import com.glean.api_client.glean_api_client.models.errors.GleanError;
import com.glean.api_client.glean_api_client.models.errors.PlatformProblemDetailException;
import com.glean.api_client.glean_api_client.models.operations.PlatformAgentsSearchResponse;
import java.io.UncheckedIOException;
import java.lang.Exception;
import java.lang.String;
import java.util.Optional;

public class Application {

    public static void main(String[] args) throws PlatformProblemDetailException, Exception {

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();
        try {

            PlatformAgentsSearchRequest req = PlatformAgentsSearchRequest.builder()
                    .name("HR Policy Agent")
                    .build();

            PlatformAgentsSearchResponse res = sdk.agents().search()
                    .request(req)
                    .call();

            if (res.platformAgentsSearchResponse().isPresent()) {
                System.out.println(res.platformAgentsSearchResponse().get());
            }
        } catch (GleanError ex) { // all SDK exceptions inherit from GleanError

            // ex.ToString() provides a detailed error message including
            // HTTP status code, headers, and error payload (if any)
            System.out.println(ex);

            // Base exception fields
            var rawResponse = ex.rawResponse();
            var headers = ex.headers();
            var contentType = headers.first("Content-Type");
            int statusCode = ex.code();
            Optional<byte[]> responseBody = ex.body();

            // different error subclasses may be thrown 
            // depending on the service call
            if (ex instanceof PlatformProblemDetailException) {
                var e = (PlatformProblemDetailException) ex;
                // Check error data fields
                e.data().ifPresent(payload -> {
                      String type = payload.type();
                      String title = payload.title();
                      // ...
                });
            }

            // An underlying cause may be provided. If the error payload 
            // cannot be deserialized then the deserialization exception 
            // will be set as the cause.
            if (ex.getCause() != null) {
                var cause = ex.getCause();
            }
        } catch (UncheckedIOException ex) {
            // handle IO error (connection, timeout, etc)
        }    }
}

Error Classes

Primary error:

  • GleanError: The base class for HTTP error responses.
Less common errors (14)

Network errors:

  • java.io.IOException (always wrapped by java.io.UncheckedIOException). Commonly encountered subclasses of IOException include java.net.ConnectException, java.net.SocketTimeoutException, EOFException (there are many more subclasses in the JDK platform).

Inherit from GleanError:

  • com.glean.api_client.glean_api_client.models.errors.PlatformProblemDetailException: Error response following RFC 9457, extended with code and documentation_url for machine-readable classification and self-service remediation. Applicable to 49 of 184 methods.*
  • com.glean.api_client.glean_api_client.models.errors.ErrorResponse: Error response returned for failed requests. Applicable to 10 of 184 methods.*
  • com.glean.api_client.glean_api_client.models.errors.ErrorInfoResponse: Error response for custom metadata operations. Applicable to 6 of 184 methods.*
  • com.glean.api_client.glean_api_client.models.errors.PlatformUnauthorizedAgentToolsProblemException: Problem detail extended with authentication_suggestions naming each tool the caller must authorize. Status code 422. Applicable to 5 of 184 methods.*
  • com.glean.api_client.glean_api_client.models.errors.CollectionError: Semantic error. Status code 422. Applicable to 3 of 184 methods.*
  • com.glean.api_client.glean_api_client.models.errors.GleanDataError: Forbidden. Applicable to 2 of 184 methods.*
  • com.glean.api_client.glean_api_client.models.errors.UnauthorizedAgentToolsError: Returned when the agent has tools the caller must authorize before the run can start. Each entry in authenticationSuggestions names one such tool; POST its serverId to /tool-servers/{serverId}/auth with returnUrl in the request body to obtain an authorizationUrl to redirect the end user to, then retry the run once OAuth completes. Status code 422. Applicable to 2 of 184 methods.*
  • com.glean.api_client.glean_api_client.models.errors.AccessRequestPermissionDeniedResponseException: Forbidden. Status code 403. Applicable to 1 of 184 methods.*

* Check the method documentation to see if the error is applicable.

Server Selection

Server Variables

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 builder methods are available when initializing the SDK client instance:

Variable BuilderMethod Default Description
instance instance(String instance) "instance-name" The instance name (typically the email domain without the TLD) that determines the deployment backend.

Example

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.PlatformAgentsSearchRequest;
import com.glean.api_client.glean_api_client.models.errors.PlatformProblemDetailException;
import com.glean.api_client.glean_api_client.models.operations.PlatformAgentsSearchResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws PlatformProblemDetailException, Exception {

        Glean sdk = Glean.builder()
                .serverIndex(0)
                .instance("<value>")
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        PlatformAgentsSearchRequest req = PlatformAgentsSearchRequest.builder()
                .name("HR Policy Agent")
                .build();

        PlatformAgentsSearchResponse res = sdk.agents().search()
                .request(req)
                .call();

        if (res.platformAgentsSearchResponse().isPresent()) {
            System.out.println(res.platformAgentsSearchResponse().get());
        }
    }
}

Override Server URL Per-Client

The default server can be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.PlatformAgentsSearchRequest;
import com.glean.api_client.glean_api_client.models.errors.PlatformProblemDetailException;
import com.glean.api_client.glean_api_client.models.operations.PlatformAgentsSearchResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws PlatformProblemDetailException, Exception {

        Glean sdk = Glean.builder()
                .serverURL("https://instance-name-be.glean.com")
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        PlatformAgentsSearchRequest req = PlatformAgentsSearchRequest.builder()
                .name("HR Policy Agent")
                .build();

        PlatformAgentsSearchResponse res = sdk.agents().search()
                .request(req)
                .call();

        if (res.platformAgentsSearchResponse().isPresent()) {
            System.out.println(res.platformAgentsSearchResponse().get());
        }
    }
}

Override Server URL Per-Operation

The server URL can also be overridden on a per-operation basis, provided a server list was specified for the operation. For example:

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.errors.ErrorInfoResponse;
import com.glean.api_client.glean_api_client.models.operations.PostRestApiIndexSubmissionsDatasourceInstanceTypeResponse;
import java.lang.Exception;
import java.util.Map;

public class Application {

    public static void main(String[] args) throws ErrorInfoResponse, Exception {

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        PostRestApiIndexSubmissionsDatasourceInstanceTypeResponse res = sdk.indexing().datasources().submit()
                .serverURL("https://instance-name-be.glean.com")
                .datasourceInstance("<value>")
                .type("<value>")
                .requestBody(Map.ofEntries(
                    Map.entry("key", "<value>"),
                    Map.entry("key1", "<value>"),
                    Map.entry("key2", "<value>")))
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object().get());
        }
    }
}

Custom HTTP Client

The Java SDK makes API calls using an HTTPClient that wraps the native HttpClient. This client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The HTTPClient interface allows you to either use the default SpeakeasyHTTPClient that comes with the SDK, or provide your own custom implementation with customized configuration such as custom executors, SSL context, connection pools, and other HTTP client settings.

The interface provides synchronous (send) methods and asynchronous (sendAsync) methods. The sendAsync method is used to power the async SDK methods and returns a CompletableFuture<HttpResponse<Blob>> for non-blocking operations.

The following example shows how to add a custom header and handle errors:

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.utils.HTTPClient;
import com.glean.api_client.glean_api_client.utils.SpeakeasyHTTPClient;
import com.glean.api_client.glean_api_client.utils.Utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;

public class Application {
    public static void main(String[] args) {
        // Create a custom HTTP client with hooks
        HTTPClient httpClient = new HTTPClient() {
            private final HTTPClient defaultClient = new SpeakeasyHTTPClient();
            
            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                // Add custom header and timeout using Utils.copy()
                HttpRequest modifiedRequest = Utils.copy(request)
                    .header("x-custom-header", "custom value")
                    .timeout(Duration.ofSeconds(30))
                    .build();
                    
                try {
                    HttpResponse<InputStream> response = defaultClient.send(modifiedRequest);
                    // Log successful response
                    System.out.println("Request successful: " + response.statusCode());
                    return response;
                } catch (Exception error) {
                    // Log error
                    System.err.println("Request failed: " + error.getMessage());
                    throw error;
                }
            }
        };

        Glean sdk = Glean.builder()
            .client(httpClient)
            .build();
    }
}
Custom HTTP Client Configuration

You can also provide a completely custom HTTP client with your own configuration:

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.utils.HTTPClient;
import com.glean.api_client.glean_api_client.utils.Blob;
import com.glean.api_client.glean_api_client.utils.ResponseWithBody;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.CompletableFuture;

public class Application {
    public static void main(String[] args) {
        // Custom HTTP client with custom configuration
        HTTPClient customHttpClient = new HTTPClient() {
            private final HttpClient client = HttpClient.newBuilder()
                .executor(Executors.newFixedThreadPool(10))
                .connectTimeout(Duration.ofSeconds(30))
                // .sslContext(customSslContext) // Add custom SSL context if needed
                .build();

            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                return client.send(request, HttpResponse.BodyHandlers.ofInputStream());
            }

            @Override
            public CompletableFuture<HttpResponse<Blob>> sendAsync(HttpRequest request) {
                // Convert response to HttpResponse<Blob> for async operations
                return client.sendAsync(request, HttpResponse.BodyHandlers.ofPublisher())
                    .thenApply(resp -> new ResponseWithBody<>(resp, Blob::from));
            }
        };

        Glean sdk = Glean.builder()
            .client(customHttpClient)
            .build();
    }
}

You can also enable debug logging on the default SpeakeasyHTTPClient:

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.utils.SpeakeasyHTTPClient;

public class Application {
    public static void main(String[] args) {
        SpeakeasyHTTPClient httpClient = new SpeakeasyHTTPClient();
        httpClient.enableDebugLogging(true);

        Glean sdk = Glean.builder()
            .client(httpClient)
            .build();
    }
}

Debugging

Debug

You can setup your SDK to emit debug logs for SDK requests and responses.

For request and response logging (especially json bodies), call enableHTTPDebugLogging(boolean) on the SDK builder like so:

SDK.builder()
    .enableHTTPDebugLogging(true)
    .build();

Example output:

Sending request: http://localhost:35123/bearer#global GET
Request headers: {Accept=[application/json], Authorization=[******], Client-Level-Header=[added by client], Idempotency-Key=[some-key], x-speakeasy-user-agent=[speakeasy-sdk/java 0.0.1 internal 0.1.0 org.openapis.openapi]}
Received response: (GET http://localhost:35123/bearer#global) 200
Response headers: {access-control-allow-credentials=[true], access-control-allow-origin=[*], connection=[keep-alive], content-length=[50], content-type=[application/json], date=[Wed, 09 Apr 2025 01:43:29 GMT], server=[gunicorn/19.9.0]}
Response body:
{
  "authenticated": true, 
  "token": "global"
}

WARNING: This logging should only be used for temporary debugging purposes. Leaving this option on in a production system could expose credentials/secrets in logs. Authorization headers are redacted by default and there is the ability to specify redacted header names via SpeakeasyHTTPClient.setRedactedHeaders.

NOTE: This is a convenience method that calls HTTPClient.enableDebugLogging(). The SpeakeasyHTTPClient honors this setting. If you are using a custom HTTP client, it is up to the custom client to honor this setting.

Another option is to set the System property -Djdk.httpclient.HttpClient.log=all. However, this second option does not log bodies.

Experimental Features and Deprecation Testing

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

Configuration Options

You can configure these options either via environment variables or SDK constructor options:

Using Environment Variables

# Set environment variables before running your application
export X_GLEAN_EXCLUDE_DEPRECATED_AFTER="2026-10-15"
export X_GLEAN_INCLUDE_EXPERIMENTAL="true"
// Environment variables are automatically read by the SDK
Glean glean = Glean.builder()
        .apiToken(System.getenv("GLEAN_API_TOKEN"))
        .serverURL("https://mycompany-be.glean.com")
        .build();

Using GleanBuilder (regen-safe)

import com.glean.api_client.glean_api_client.hooks.GleanBuilder;

Glean glean = GleanBuilder.create()
        .apiToken(System.getenv("GLEAN_API_TOKEN"))
        .serverURL("https://mycompany-be.glean.com")
        .excludeDeprecatedAfter("2026-10-15")
        .includeExperimental(true)
        .build();

Note: GleanBuilder is preserved across SDK regenerations. Generated builder options may change or be removed by regeneration.

Option Reference

Option Environment Variable Type Description
excludeDeprecatedAfter X_GLEAN_EXCLUDE_DEPRECATED_AFTER String (date) Exclude API endpoints that will be deprecated after this date (format: YYYY-MM-DD). Use this to test your integration against upcoming deprecations.
includeExperimental X_GLEAN_INCLUDE_EXPERIMENTAL boolean 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.

Jackson Configuration

The SDK ships with a pre-configured Jackson ObjectMapper accessible via JSON.getMapper(). It is set up with type modules, strict deserializers, and the feature flags needed for full SDK compatibility (including ISO-8601 OffsetDateTime serialization):

import com.glean.api_client.glean_api_client.utils.JSON;

String json = JSON.getMapper().writeValueAsString(response);

To compose with your own ObjectMapper, register the provided GleanApiClientJacksonModule, which bundles all the same modules and feature flags as a single plug-and-play module:

import com.glean.api_client.glean_api_client.utils.GleanApiClientJacksonModule;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper myMapper = new ObjectMapper()
    .registerModule(new GleanApiClientJacksonModule());

String json = myMapper.writeValueAsString(response);

Development

Maturity

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.

Contributions

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.

SDK Created by Speakeasy

About

The official Java library for the Glean API

Resources

Readme
MIT license

Contributing

Contributing
Activity
Custom properties

Stars

9 stars

Watchers

3 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.