| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
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.
This SDK combines both the Client and Indexing API namespaces into a single unified package:
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.
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.16.0'Maven:
<dependency>
<groupId>com.glean.api-client</groupId>
<artifactId>glean-api-client</artifactId>
<version>0.16.0</version>
</dependency>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.signingOn Windows:
gradlew.bat publishToMavenLocal -Pskip.signingpackage 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());
}
}
}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());
}
}
}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());
}
});
}
}When a response field is a union model:
For full model-specific examples (including Java 11/16/21 variants), see each union model's Supported Types section in the generated model docs.
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:
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?
Integration with Popular Libraries:
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 OperationsAsync support is available for:
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());
}
}
}Glean supports different authentication methods depending on which API namespace you're using:
The Client namespace supports two authentication methods:
Manually Provisioned API Tokens
OAuth
The Indexing namespace supports only one authentication method:
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 methodsaddOrUpdate - 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
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
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) |
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)
} }
}Primary error:
Network errors:
Inherit from GleanError:
* Check the method documentation to see if the error is applicable.
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. |
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());
}
}
}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());
}
}
}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());
}
}
}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();
}
}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();
}
}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.
The SDK provides options to test upcoming API changes before they become the default behavior. This is useful for:
You can configure these options either via environment variables or SDK constructor options:
# 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();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 | 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.
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);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.
| Back | FazBrowse Home | New Git URL |