This documentation is automatically synced from the Java SDK GitHub repository.
MCP Server
Use the Stagehand MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.Note: You may need to set environment variables in your MCP client.The REST API documentation can be found on docs.stagehand.dev. Javadocs are available on javadoc.io.
Installation
Gradle
Maven
Requirements
This library requires Java 8 through Java 21. Java 22+ is not currently supported.Running the Example
A complete working example is available atstagehand-java-example/src/main/java/com/stagehand/api/example/Main.java.
To run it, first export the required environment variables, then use Gradle:
Usage
This example demonstrates the full Stagehand workflow: starting a session, navigating to a page, observing possible actions, acting on elements, extracting data, and running an autonomous agent.Client configuration
Configure the client using system properties or environment variables:| Setter | System property | Environment variable | Required | Default value |
|---|---|---|---|---|
browserbaseApiKey | stagehand.browserbaseApiKey | BROWSERBASE_API_KEY | true | - |
browserbaseProjectId | stagehand.browserbaseProjectId | BROWSERBASE_PROJECT_ID | true | - |
modelApiKey | stagehand.modelApiKey | MODEL_API_KEY | true | - |
baseUrl | stagehand.baseUrl | STAGEHAND_BASE_URL | true | "https://api.stagehand.browserbase.com" |
[!TIP] Don’t create more than one client in the same application. Each client has a connection pool and thread pools, which are more efficient to share between requests.
Modifying configuration
To temporarily use a modified client configuration, while reusing the same connection and thread pools, callwithOptions() on any client or service:
withOptions() method does not affect the original client or service.
Requests and responses
To send a request to the Stagehand API, build an instance of someParams class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class.
For example, client.sessions().act(...) should be called with an instance of SessionActParams, and it will return an instance of SessionActResponse.
Immutability
Each class in the SDK has an associated builder or factory method for constructing it. Each class is immutable once constructed. If the class has an associated builder, then it has atoBuilder() method, which can be used to convert it back to a builder for making a modified copy.
Because each class is immutable, builder modification will never affect already built class instances.
Asynchronous execution
The default client is synchronous. To switch to asynchronous execution, call theasync() method:
CompletableFutures.
Streaming
The SDK defines methods that return response “chunk” streams, where each chunk can be individually processed as soon as it arrives instead of waiting on the full response. Streaming methods generally correspond to SSE or JSONL responses. Some of these methods may have streaming and non-streaming variants, but a streaming method will always have aStreaming suffix in its name, even if it doesn’t have a non-streaming variant.
These streaming methods return StreamResponse for synchronous clients:
AsyncStreamResponse for asynchronous clients:
Executor to stream without blocking the current thread. This default is suitable for most purposes.
To use a different Executor, configure the subscription using the executor parameter:
streamHandlerExecutor method:
Raw responses
The SDK defines methods that deserialize responses into instances of Java classes. However, these methods don’t provide access to the response headers, status code, or the raw response body. To access this data, prefix any HTTP method call on a client or service withwithRawResponse():
Error handling
The SDK throws custom unchecked exception types:-
StagehandServiceException: Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code:SseExceptionis thrown for errors encountered during SSE streaming after a successful initial HTTP response. -
StagehandIoException: I/O networking errors. -
StagehandRetryableException: Generic error indicating a failure that could be retried by the client. -
StagehandInvalidDataException: Failure to interpret successfully parsed data. For example, when accessing a property that’s supposed to be required, but the API unexpectedly omitted it from the response. -
StagehandException: Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class.
Logging
The SDK uses the standard OkHttp logging interceptor. Enable logging by setting theSTAGEHAND_LOG environment variable to info:
debug for more verbose logging:
ProGuard and R8
Although the SDK uses reflection, it is still usable with ProGuard and R8 becausestagehand-java-core is published with a configuration file containing keep rules.
ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.
Jackson
The SDK depends on Jackson for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default. The SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config). If the SDK threw an exception, but you’re certain the version is compatible, then disable the version check using thecheckJacksonVersionCompatibility on StagehandOkHttpClient or StagehandOkHttpClientAsync.
[!CAUTION] We make no guarantee that the SDK works correctly when the Jackson version check is disabled.
Network options
Retries
The SDK automatically retries 2 times by default, with a short exponential backoff between requests. Only the following error types are retried:- Connection errors (for example, due to a network connectivity problem)
- 408 Request Timeout
- 409 Conflict
- 429 Rate Limit
- 5xx Internal
maxRetries method:
Timeouts
Requests time out after 1 minute by default. To set a custom timeout, configure the method call using thetimeout method:
Proxies
To route requests through a proxy, configure the client using theproxy method:
HTTPS
[!NOTE] Most applications should not call these methods, and instead use the system defaults. The defaults include special optimizations that can be lost if the implementations are modified.To configure how HTTPS connections are secured, configure the client using the
sslSocketFactory, trustManager, and hostnameVerifier methods:
Custom HTTP client
The SDK consists of three artifacts:stagehand-java-core- Contains core SDK logic
- Does not depend on OkHttp
- Exposes
StagehandClient,StagehandClientAsync,StagehandClientImpl, andStagehandClientAsyncImpl, all of which can work with any HTTP client
stagehand-java-client-okhttp- Depends on OkHttp
- Exposes
StagehandOkHttpClientandStagehandOkHttpClientAsync, which provide a way to constructStagehandClientImplandStagehandClientAsyncImpl, respectively, using OkHttp
stagehand-java- Depends on and exposes the APIs of both
stagehand-java-coreandstagehand-java-client-okhttp - Does not have its own logic
- Depends on and exposes the APIs of both
Customized OkHttpClient
[!TIP] Try the available network options before replacing the default client.To use a customized
OkHttpClient:
- Replace your
stagehand-javadependency withstagehand-java-core - Copy
stagehand-java-client-okhttp’sOkHttpClientclass into your code and customize it - Construct
StagehandClientImplorStagehandClientAsyncImpl, similarly toStagehandOkHttpClientorStagehandOkHttpClientAsync, using your customized client
Completely custom HTTP client
To use a completely custom HTTP client:- Replace your
stagehand-javadependency withstagehand-java-core - Write a class that implements the
HttpClientinterface - Construct
StagehandClientImplorStagehandClientAsyncImpl, similarly toStagehandOkHttpClientorStagehandOkHttpClientAsync, using your new client class
Undocumented API functionality
The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.Parameters
To set undocumented parameters, call theputAdditionalHeader, putAdditionalQueryParam, or putAdditionalBodyProperty methods on any Params class:
_additionalHeaders(), _additionalQueryParams(), and _additionalBodyProperties() methods.
To set undocumented parameters on nested headers, query params, or body classes, call the putAdditionalProperty method on the nested class:
_additionalProperties() method.
To set a documented parameter or property to an undocumented or not yet supported value, pass a JsonValue object to its setter:
JsonValue is using its from(...) method:
Builder class’s build method will throw IllegalStateException if any required parameter or property is unset.
To forcibly omit a required parameter or property, pass JsonMissing:
Response properties
To access undocumented response properties, call the_additionalProperties() method:
_ prefixed method:
Response validation
In rare cases, the API may return a response that doesn’t match the expected type. For example, the SDK may expect a property to contain aString, but the API could return something else.
By default, the SDK will not throw an exception in this case. It will throw StagehandInvalidDataException only if you directly access the property.
If you would prefer to check that the response is completely well-typed upfront, then either call validate():
responseValidation method:
FAQ
Why don’t you use plain enum classes?
Java enum classes are not trivially forwards compatible. Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.
Why do you represent fields using JsonField<T> instead of just plain T?
Using JsonField<T> enables a few features:
- Allowing usage of undocumented API functionality
- Lazily validating the API response against the expected shape
- Representing absent vs explicitly null values
Why don’t you use data classes?
It is not backwards compatible to add new fields to a data class and we don’t want to introduce a breaking change every time we add a field to a class.
Why don’t you use checked exceptions?
Checked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason. Checked exceptions:- Are verbose to handle
- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error
- Are tedious to propagate due to the function coloring problem
- Don’t play well with lambdas (also due to the function coloring problem)
Semantic versioning
This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:- Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
- Changes that we do not expect to impact the vast majority of users in practice.

