Hathora Cloud API: Welcome to the Hathora Cloud API documentation! Learn how to use the Hathora Cloud APIs to build and scale your game servers globally.
- SDK Installation
- SDK Example Usage
- Available Resources and Operations
- Global Parameters
- Error Handling
- Server Selection
- Asynchronous Support
- Authentication
- Custom HTTP Client
- Debugging
JDK 11 or later is required.
The samples below show how a published SDK artifact is used:
Gradle:
implementation 'dev.hathora:cloud-sdk:3.3.0'Maven:
<dependency>
<groupId>dev.hathora</groupId>
<artifactId>cloud-sdk</artifactId>
<version>3.3.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 dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.models.errors.ApiError;
import dev.hathora.cloud_sdk.models.operations.CreateAppResponse;
import dev.hathora.cloud_sdk.models.shared.*;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws ApiError, Exception {
HathoraCloud sdk = HathoraCloud.builder()
.orgId("org-6f706e83-0ec1-437a-9a46-7d4281eb2f39")
.security(Security.builder()
.hathoraDevToken(System.getenv().getOrDefault("HATHORA_DEV_TOKEN", ""))
.build())
.build();
CreateAppResponse res = sdk.appsV2().createApp()
.createAppConfig(CreateAppConfig.builder()
.appName("minecraft")
.authConfiguration(AuthConfiguration.builder()
.build())
.build())
.call();
if (res.application().isPresent()) {
// handle response
}
}
}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 dev.hathora.cloud_sdk.AsyncHathoraCloud;
import dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.models.operations.async.CreateAppResponse;
import dev.hathora.cloud_sdk.models.shared.*;
import java.util.concurrent.CompletableFuture;
public class Application {
public static void main(String[] args) {
AsyncHathoraCloud sdk = HathoraCloud.builder()
.orgId("org-6f706e83-0ec1-437a-9a46-7d4281eb2f39")
.security(Security.builder()
.hathoraDevToken(System.getenv().getOrDefault("HATHORA_DEV_TOKEN", ""))
.build())
.build()
.async();
CompletableFuture<CreateAppResponse> resFut = sdk.appsV2().createApp()
.createAppConfig(CreateAppConfig.builder()
.appName("minecraft")
.authConfiguration(AuthConfiguration.builder()
.build())
.build())
.call();
resFut.thenAccept(res -> {
if (res.application().isPresent()) {
// handle response
}
});
}
}Available methods
createAppV1Deprecated- CreateAppV1Deprecated⚠️ DeprecateddeleteAppV1Deprecated- DeleteAppV1Deprecated⚠️ DeprecatedgetAppInfoV1Deprecated- GetAppInfoV1Deprecated⚠️ DeprecatedgetAppsV1Deprecated- GetAppsV1Deprecated⚠️ DeprecatedupdateAppV1Deprecated- UpdateAppV1Deprecated⚠️ Deprecated
- createApp - CreateApp
- deleteApp - DeleteApp
- getApp - GetApp
- getApps - GetApps
- patchApp - PatchApp
- updateApp - UpdateApp
- loginAnonymous - LoginAnonymous
- loginGoogle - LoginGoogle
- loginNickname - LoginNickname
getBalance- GetBalance⚠️ Deprecated- getInvoices - GetInvoices
- getPaymentMethod - GetPaymentMethod
- getUpcomingInvoiceItems - GetUpcomingInvoiceItems
- getUpcomingInvoiceTotal - GetUpcomingInvoiceTotal
- initStripeCustomerPortalUrl - InitStripeCustomerPortalUrl
createBuildDeprecated- CreateBuildDeprecated⚠️ DeprecateddeleteBuildDeprecated- DeleteBuildDeprecated⚠️ DeprecatedgetBuildInfoDeprecated- GetBuildInfoDeprecated⚠️ DeprecatedgetBuildsDeprecated- GetBuildsDeprecated⚠️ DeprecatedrunBuildDeprecated- RunBuildDeprecated⚠️ Deprecated
createBuildV2Deprecated- CreateBuildV2Deprecated⚠️ DeprecatedcreateBuildWithUploadUrlV2Deprecated- CreateBuildWithUploadUrlV2Deprecated⚠️ DeprecatedcreateWithMultipartUploadsV2Deprecated- CreateWithMultipartUploadsV2Deprecated⚠️ DeprecateddeleteBuildV2Deprecated- DeleteBuildV2Deprecated⚠️ DeprecatedgetBuildInfoV2Deprecated- GetBuildInfoV2Deprecated⚠️ DeprecatedgetBuildsV2Deprecated- GetBuildsV2Deprecated⚠️ DeprecatedrunBuildV2Deprecated- RunBuildV2Deprecated⚠️ Deprecated
- createBuild - CreateBuild
- createBuildRegistry - CreateBuildRegistry
- deleteBuild - DeleteBuild
- getBuild - GetBuild
- getBuilds - GetBuilds
- runBuild - RunBuild
- runBuildRegistry - RunBuildRegistry
createDeploymentV1Deprecated- CreateDeploymentV1Deprecated⚠️ DeprecatedgetDeploymentInfoV1Deprecated- GetDeploymentInfoV1Deprecated⚠️ DeprecatedgetDeploymentsV1Deprecated- GetDeploymentsV1Deprecated⚠️ DeprecatedgetLatestDeploymentV1Deprecated- GetLatestDeploymentV1Deprecated⚠️ Deprecated
createDeploymentV2Deprecated- CreateDeploymentV2Deprecated⚠️ DeprecatedgetDeploymentInfoV2Deprecated- GetDeploymentInfoV2Deprecated⚠️ DeprecatedgetDeploymentsV2Deprecated- GetDeploymentsV2Deprecated⚠️ DeprecatedgetLatestDeploymentV2Deprecated- GetLatestDeploymentV2Deprecated⚠️ Deprecated
- createDeployment - CreateDeployment
- getDeployment - GetDeployment
- getDeployments - GetDeployments
- getLatestDeployment - GetLatestDeployment
getPingServiceEndpointsDeprecated- GetPingServiceEndpointsDeprecated⚠️ Deprecated
- getPingServiceEndpoints - GetPingServiceEndpoints
- createFleetDeprecated - CreateFleetDeprecated
- getFleetDeprecated - GetFleetDeprecated
- getFleetMetricsDeprecated - GetFleetMetricsDeprecated
- getFleetRegionDeprecated - GetFleetRegionDeprecated
- getFleetRegionMetricsDeprecated - GetFleetRegionMetricsDeprecated
- getFleetsDeprecated - GetFleetsDeprecated
- updateFleetDeprecated - UpdateFleetDeprecated
- updateFleetRegionDeprecated - UpdateFleetRegionDeprecated
- createFleet - CreateFleet
- getFleet - GetFleet
- getFleetMetrics - GetFleetMetrics
- getFleetRegion - GetFleetRegion
- getFleetRegionMetrics - GetFleetRegionMetrics
- getFleets - GetFleets
- getNodeShapes - GetNodeShapes
- updateFleet - UpdateFleet
- updateFleetRegion - UpdateFleetRegion
createPrivateLobbyDeprecated- CreatePrivateLobbyDeprecated⚠️ DeprecatedcreatePublicLobbyDeprecated- CreatePublicLobbyDeprecated⚠️ DeprecatedlistActivePublicLobbiesDeprecatedV1- ListActivePublicLobbiesDeprecatedV1⚠️ Deprecated
createLobbyDeprecated- CreateLobbyDeprecated⚠️ DeprecatedcreateLocalLobby- CreateLocalLobby⚠️ DeprecatedcreatePrivateLobby- CreatePrivateLobby⚠️ DeprecatedcreatePublicLobby- CreatePublicLobby⚠️ DeprecatedgetLobbyInfo- GetLobbyInfo⚠️ DeprecatedlistActivePublicLobbiesDeprecatedV2- ListActivePublicLobbiesDeprecatedV2⚠️ DeprecatedsetLobbyState- SetLobbyState⚠️ Deprecated
- createLobby - CreateLobby
- getLobbyInfoByRoomId - GetLobbyInfoByRoomId
- getLobbyInfoByShortCode - GetLobbyInfoByShortCode
- listActivePublicLobbies - ListActivePublicLobbies
- downloadLogForProcess - DownloadLogForProcess
- getLogsForProcess - GetLogsForProcess
- sendVerificationEmail - SendVerificationEmail
getMetricsDeprecated- GetMetricsDeprecated⚠️ Deprecated
- getNode - GetNode
- listProvisionedNodes - ListProvisionedNodes
- acceptInvite - AcceptInvite
- getOrgMembers - GetOrgMembers
- getOrgPendingInvites - GetOrgPendingInvites
- getOrgs - GetOrgs
- getUsageLimits - GetUsageLimits
- getUserPendingInvites - GetUserPendingInvites
- inviteUser - InviteUser
- rejectInvite - RejectInvite
- rescindInvite - RescindInvite
- updateUserInvite - UpdateUserInvite
getProcessInfoDeprecated- GetProcessInfoDeprecated⚠️ DeprecatedgetRunningProcesses- GetRunningProcesses⚠️ DeprecatedgetStoppedProcesses- GetStoppedProcesses⚠️ Deprecated
createProcessV2Deprecated- CreateProcessV2Deprecated⚠️ DeprecatedgetLatestProcessesV2Deprecated- GetLatestProcessesV2Deprecated⚠️ DeprecatedgetProcessInfoV2Deprecated- GetProcessInfoV2Deprecated⚠️ DeprecatedgetProcessesCountExperimentalV2Deprecated- GetProcessesCountExperimentalV2Deprecated⚠️ DeprecatedstopProcessV2Deprecated- StopProcessV2Deprecated⚠️ Deprecated
- createProcess - CreateProcess
- getLatestProcesses - GetLatestProcesses
- getProcess - GetProcess
- getProcessMetrics - GetProcessMetrics
- getProcessesCountExperimental - GetProcessesCountExperimental
- stopProcess - StopProcess
createRoomDeprecated- CreateRoomDeprecated⚠️ DeprecateddestroyRoomDeprecated- DestroyRoomDeprecated⚠️ DeprecatedgetActiveRoomsForProcessDeprecated- GetActiveRoomsForProcessDeprecated⚠️ DeprecatedgetConnectionInfoDeprecated- GetConnectionInfoDeprecated⚠️ DeprecatedgetInactiveRoomsForProcessDeprecated- GetInactiveRoomsForProcessDeprecated⚠️ DeprecatedgetRoomInfoDeprecated- GetRoomInfoDeprecated⚠️ DeprecatedsuspendRoomDeprecated- SuspendRoomDeprecated⚠️ Deprecated
- createRoom - CreateRoom
- destroyRoom - DestroyRoom
- getActiveRoomsForProcess - GetActiveRoomsForProcess
- getConnectionInfo - GetConnectionInfo
- getInactiveRoomsForProcess - GetInactiveRoomsForProcess
- getRoomInfo - GetRoomInfo
- resumeRoom - ResumeRoom
suspendRoomV2Deprecated- SuspendRoomV2Deprecated⚠️ Deprecated- updateRoomConfig - UpdateRoomConfig
- createOrgToken - CreateOrgToken
- getOrgTokens - GetOrgTokens
- revokeOrgToken - RevokeOrgToken
Certain parameters are configured globally. These parameters may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, These global values will be used as defaults on the operations that use them. When such operations are called, there is a place in each to override the global value, if needed.
For example, you can set appId to "app-af469a92-5b45-4565-b3c4-b79878de67d2" at SDK initialization and then you do not have to pass the same value on calls to operations like createApp. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.
The following global parameters are available.
| Name | Type | Description |
|---|---|---|
| appId | java.lang.String | The appId parameter. |
| orgId | java.lang.String | The orgId parameter. |
package hello.world;
import dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.models.errors.ApiError;
import dev.hathora.cloud_sdk.models.operations.CreateAppResponse;
import dev.hathora.cloud_sdk.models.shared.*;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws ApiError, Exception {
HathoraCloud sdk = HathoraCloud.builder()
.orgId("org-6f706e83-0ec1-437a-9a46-7d4281eb2f39")
.appId("app-af469a92-5b45-4565-b3c4-b79878de67d2")
.security(Security.builder()
.hathoraDevToken(System.getenv().getOrDefault("HATHORA_DEV_TOKEN", ""))
.build())
.build();
CreateAppResponse res = sdk.appsV2().createApp()
.createAppConfig(CreateAppConfig.builder()
.appName("minecraft")
.authConfiguration(AuthConfiguration.builder()
.build())
.build())
.call();
if (res.application().isPresent()) {
// handle response
}
}
}Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.
HathoraCloudException 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 dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.models.errors.ApiError;
import dev.hathora.cloud_sdk.models.errors.HathoraCloudException;
import dev.hathora.cloud_sdk.models.operations.CreateAppResponse;
import dev.hathora.cloud_sdk.models.shared.*;
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 ApiError, Exception {
HathoraCloud sdk = HathoraCloud.builder()
.orgId("org-6f706e83-0ec1-437a-9a46-7d4281eb2f39")
.security(Security.builder()
.hathoraDevToken(System.getenv().getOrDefault("HATHORA_DEV_TOKEN", ""))
.build())
.build();
try {
CreateAppResponse res = sdk.appsV2().createApp()
.createAppConfig(CreateAppConfig.builder()
.appName("minecraft")
.authConfiguration(AuthConfiguration.builder()
.build())
.build())
.call();
if (res.application().isPresent()) {
// handle response
}
} catch (HathoraCloudException ex) { // all SDK exceptions inherit from HathoraCloudException
// 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 ApiError) {
var e = (ApiError) ex;
// Check error data fields
e.data().ifPresent(payload -> {
String message = payload.message();
});
}
// 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 errors:
HathoraCloudException: The base class for HTTP error responses.
Less common errors (6)
Network errors:
java.io.IOException(always wrapped byjava.io.UncheckedIOException). Commonly encountered subclasses ofIOExceptionincludejava.net.ConnectException,java.net.SocketTimeoutException,EOFException(there are many more subclasses in the JDK platform).
Inherit from HathoraCloudException:
* Check the method documentation to see if the error is applicable.
You can override the default server globally using the .serverIndex(int serverIdx) builder method when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:
| # | Server | Description |
|---|---|---|
| 0 | https://api.hathora.dev |
|
| 1 | / |
package hello.world;
import dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.models.errors.ApiError;
import dev.hathora.cloud_sdk.models.operations.CreateAppResponse;
import dev.hathora.cloud_sdk.models.shared.*;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws ApiError, Exception {
HathoraCloud sdk = HathoraCloud.builder()
.serverIndex(0)
.orgId("org-6f706e83-0ec1-437a-9a46-7d4281eb2f39")
.security(Security.builder()
.hathoraDevToken(System.getenv().getOrDefault("HATHORA_DEV_TOKEN", ""))
.build())
.build();
CreateAppResponse res = sdk.appsV2().createApp()
.createAppConfig(CreateAppConfig.builder()
.appName("minecraft")
.authConfiguration(AuthConfiguration.builder()
.build())
.build())
.call();
if (res.application().isPresent()) {
// handle response
}
}
}The default server can also be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:
package hello.world;
import dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.models.errors.ApiError;
import dev.hathora.cloud_sdk.models.operations.CreateAppResponse;
import dev.hathora.cloud_sdk.models.shared.*;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws ApiError, Exception {
HathoraCloud sdk = HathoraCloud.builder()
.serverURL("https://api.hathora.dev")
.orgId("org-6f706e83-0ec1-437a-9a46-7d4281eb2f39")
.security(Security.builder()
.hathoraDevToken(System.getenv().getOrDefault("HATHORA_DEV_TOKEN", ""))
.build())
.build();
CreateAppResponse res = sdk.appsV2().createApp()
.createAppConfig(CreateAppConfig.builder()
.appName("minecraft")
.authConfiguration(AuthConfiguration.builder()
.build())
.build())
.call();
if (res.application().isPresent()) {
// handle response
}
}
}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()andcallAsPublisherUnwrapped() - 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
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
hathoraDevToken |
http | HTTP Bearer |
You can set the security parameters through the security builder method when initializing the SDK client instance. For example:
package hello.world;
import dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.models.errors.ApiError;
import dev.hathora.cloud_sdk.models.operations.CreateAppResponse;
import dev.hathora.cloud_sdk.models.shared.*;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws ApiError, Exception {
HathoraCloud sdk = HathoraCloud.builder()
.security(Security.builder()
.hathoraDevToken(System.getenv().getOrDefault("HATHORA_DEV_TOKEN", ""))
.build())
.orgId("org-6f706e83-0ec1-437a-9a46-7d4281eb2f39")
.build();
CreateAppResponse res = sdk.appsV2().createApp()
.createAppConfig(CreateAppConfig.builder()
.appName("minecraft")
.authConfiguration(AuthConfiguration.builder()
.build())
.build())
.call();
if (res.application().isPresent()) {
// handle response
}
}
}Some operations in this SDK require the security scheme to be specified at the request level. For example:
package hello.world;
import dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.models.errors.ApiError;
import dev.hathora.cloud_sdk.models.operations.*;
import dev.hathora.cloud_sdk.models.shared.*;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws ApiError, Exception {
HathoraCloud sdk = HathoraCloud.builder()
.appId("app-af469a92-5b45-4565-b3c4-b79878de67d2")
.build();
CreateLobbyRequest req = CreateLobbyRequest.builder()
.createLobbyV3Params(CreateLobbyV3Params.builder()
.region(Region.DUBAI)
.visibility(LobbyVisibility.PRIVATE)
.roomConfig("{\"name\":\"my-room\"}")
.build())
.roomId("2swovpy1fnunu")
.shortCode("LFG4")
.build();
CreateLobbyResponse res = sdk.lobbiesV3().createLobby()
.request(req)
.security(CreateLobbySecurity.builder()
.playerAuth(System.getenv().getOrDefault("PLAYER_AUTH", ""))
.build())
.call();
if (res.lobbyV3().isPresent()) {
// handle response
}
}
}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 dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.utils.HTTPClient;
import dev.hathora.cloud_sdk.utils.SpeakeasyHTTPClient;
import dev.hathora.cloud_sdk.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;
}
}
};
HathoraCloud sdk = HathoraCloud.builder()
.client(httpClient)
.build();
}
}Custom HTTP Client Configuration
You can also provide a completely custom HTTP client with your own configuration:
import dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.utils.HTTPClient;
import dev.hathora.cloud_sdk.utils.Blob;
import dev.hathora.cloud_sdk.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));
}
};
HathoraCloud sdk = HathoraCloud.builder()
.client(customHttpClient)
.build();
}
}You can also enable debug logging on the default SpeakeasyHTTPClient:
import dev.hathora.cloud_sdk.HathoraCloud;
import dev.hathora.cloud_sdk.utils.SpeakeasyHTTPClient;
public class Application {
public static void main(String[] args) {
SpeakeasyHTTPClient httpClient = new SpeakeasyHTTPClient();
httpClient.enableDebugLogging(true);
HathoraCloud sdk = HathoraCloud.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 should only 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.
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. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release !