The Clerk Java library provides convenient access to the Clerk REST API from from a Java application. The library includes type definitions for all request params and response fields, and is powered by Apache Httpclient.
Clerk Backend API: The Clerk REST Backend API, meant to be accessed by backend servers.
When the API changes in a way that isn't compatible with older versions, a new version is released.
Each version is identified by its release date, e.g. 2025-04-10. For more information, please see Clerk API Versions.
Please see https://clerk.com/docs for more information.
More information about the API can be found at https://clerk.com/docs
- SDK Installation
- SDK Example Usage
- Authentication
- Request Authentication
- Available Resources and Operations
- Retries
- Error Handling
- Server Selection
- Custom HTTP Client
- Debugging
- Development
JDK 11 or later is required.
The samples below show how a published SDK artifact is used:
Gradle:
implementation 'com.clerk:backend-api:4.0.0'Maven:
<dependency>
<groupId>com.clerk</groupId>
<artifactId>backend-api</artifactId>
<version>4.0.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.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.errors.ClerkErrors;
import com.clerk.backend_api.models.operations.GetEmailAddressResponse;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws ClerkErrors, Exception {
Clerk sdk = Clerk.builder()
.bearerAuth(System.getenv().getOrDefault("BEARER_AUTH", ""))
.build();
GetEmailAddressResponse res = sdk.emailAddresses().get()
.emailAddressId("<id>")
.call();
if (res.emailAddress().isPresent()) {
// handle response
}
}
}This SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
bearerAuth |
http | HTTP Bearer |
To authenticate with the API the bearerAuth parameter must be set when initializing the SDK client instance. For example:
package hello.world;
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialResponse;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws Exception {
Clerk sdk = Clerk.builder()
.bearerAuth(System.getenv().getOrDefault("BEARER_AUTH", ""))
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.call();
// handle response
}
}Use the authenticateRequest method to authenticate a request from your app's frontend (when using a Clerk frontend SDK) to Clerk's Backend API. For example the following utility function checks if the user is effectively signed in:
import java.net.http.HttpRequest;
import com.clerk.backend_api.helpers.security.AuthenticateRequest;
import com.clerk.backend_api.helpers.security.models.AuthenticateRequestOptions;
import com.clerk.backend_api.helpers.security.models.RequestState;
public class UserAuthentication {
public static boolean isSignedIn(HttpRequest request) {
RequestState requestState = AuthenticateRequest.authenticateRequest(request, AuthenticateRequestOptions
.secretKey(System.getenv("CLERK_SECRET_KEY"))
.authorizedParty("https://example.com")
.build());
return requestState.isSignedIn();
}If the request is correctly authenticated, the token's claims are made available in requestState.claims(). Otherwise the reason for the token verification failure is given by requestState.reason().
The SDK also supports machine-to-machine authentication through machine tokens. To authenticate machine requests, specify the accepted token types when building the authentication options:
import java.net.http.HttpRequest;
import com.clerk.backend_api.helpers.security.AuthenticateRequest;
import com.clerk.backend_api.helpers.security.models.AuthenticateRequestOptions;
import com.clerk.backend_api.helpers.security.models.RequestState;
import java.util.Arrays;
public class MachineAuthentication {
public static boolean isAuthenticated(HttpRequest request) {
RequestState requestState = AuthenticateRequest.authenticateRequest(request, AuthenticateRequestOptions
.secretKey(System.getenv("CLERK_SECRET_KEY"))
.acceptsTokens(Arrays.asList("oauth_token"))
.build());
return requestState.isSignedIn();
}
}Available methods
- list - List all identifiers on the allow-list
- create - Add identifier to the allow-list
- delete - Delete identifier from allow-list
- updateInstanceSettings - Update instance settings
updateProductionInstanceDomain- Update production instance domain⚠️ Deprecated
- extendSubscriptionItemFreeTrial - Extend free trial for a subscription item
- listStatements - List all billing statements
- getStatement - Retrieve a billing statement
- getStatementPaymentAttempts - List payment attempts for a billing statement
- list - List all identifiers on the block-list
- create - Add identifier to the block-list
- delete - Delete identifier from block-list
- listPlans - List all commerce plans
- listSubscriptionItems - List all subscription items
- cancelSubscriptionItem - Cancel a subscription item
- list - List all instance domains
- add - Add a domain
- delete - Delete a satellite domain
- update - Update a domain
- create - Create an email address
- get - Retrieve an email address
- delete - Delete an email address
- update - Update an email address
upsert- Update a template for a given type and slug⚠️ Deprecated
list- List all templates⚠️ Deprecatedget- Retrieve a template⚠️ Deprecatedrevert- Revert a template⚠️ DeprecatedtoggleTemplateDelivery- Toggle the delivery by Clerk for a template of a given type and slug⚠️ Deprecated
- get - Fetch the current instance
- update - Update instance settings
- updateRestrictions - Update instance restrictions
- changeDomain - Update production instance domain
- updateOrganizationSettings - Update instance organization settings
- create - Create an invitation
- list - List all invitations
- bulkCreate - Create multiple invitations
- revoke - Revokes an invitation
- getJWKS - Retrieve the JSON Web Key Set of the instance
- list - List all templates
- create - Create a JWT template
- get - Retrieve a template
- update - Update a JWT template
- delete - Delete a Template
- createToken - Create a M2M Token
- listTokens - Get M2M Tokens
- revokeToken - Revoke a M2M Token
- verifyToken - Verify a M2M Token
- list - Get a list of machines for an instance
- create - Create a machine
- get - Retrieve a machine
- update - Update a machine
- delete - Delete a machine
- getSecretKey - Retrieve a machine secret key
- rotateSecretKey - Rotate a machine's secret key
- createScope - Create a machine scope
- deleteScope - Delete a machine scope
- getPublicInterstitial - Returns the markup for the interstitial page
- verify - Verify an OAuth Access Token
- list - Get a list of OAuth applications for an instance
- create - Create an OAuth application
- get - Retrieve an OAuth application by ID
- update - Update an OAuth application
- delete - Delete an OAuth application
- rotateSecret - Rotate the client secret of the given OAuth application
- create - Create a new organization domain.
- list - Get a list of all domains of an organization.
- update - Update an organization domain.
- delete - Remove a domain from an organization.
- listAll - List all organization domains
- getAll - Get a list of organization invitations for the current instance
- create - Create and send an organization invitation
- list - Get a list of organization invitations
- bulkCreate - Bulk create and send organization invitations
listPending- Get a list of pending organization invitations⚠️ Deprecated- get - Retrieve an organization invitation by ID
- revoke - Revoke a pending organization invitation
- create - Create a new organization membership
- list - Get a list of all members of an organization
- update - Update an organization membership
- delete - Remove a member from an organization
- updateMetadata - Merge and update organization membership metadata
- list - Get a list of organizations for an instance
- create - Create an organization
- get - Retrieve an organization by ID or slug
- update - Update an organization
- delete - Delete an organization
- mergeMetadata - Merge and update metadata for an organization
- uploadLogo - Upload a logo for the organization
- deleteLogo - Delete the organization's logo.
- getBillingSubscription - Retrieve an organization's billing subscription
- create - Create a phone number
- get - Retrieve a phone number
- delete - Delete a phone number
- update - Update a phone number
- verify - Verify the proxy configuration for your domain
- list - List all redirect URLs
- create - Create a redirect URL
- get - Retrieve a redirect URL
- delete - Delete a redirect URL
- list - Get a list of SAML Connections for an instance
- create - Create a SAML Connection
- get - Retrieve a SAML Connection by ID
- update - Update a SAML Connection
- delete - Delete a SAML Connection
- list - List all sessions
- create - Create a new active session
- get - Retrieve a session
- refresh - Refresh a session
- revoke - Revoke a session
- createToken - Create a session token
- createTokenFromTemplate - Create a session token from a JWT template
preview- Preview changes to a template⚠️ Deprecated
- create - Retrieve a new testing token
- list - List all users
- create - Create a new user
- count - Count users
- get - Retrieve a user
- update - Update a user
- delete - Delete a user
- ban - Ban a user
- unban - Unban a user
- bulkBan - Ban multiple users
- bulkUnban - Unban multiple users
- lock - Lock a user
- unlock - Unlock a user
- setProfileImage - Set user profile image
- deleteProfileImage - Delete user profile image
- updateMetadata - Merge and update a user's metadata
- getBillingSubscription - Retrieve a user's billing subscription
- getOAuthAccessToken - Retrieve the OAuth access token of a user
- getOrganizationMemberships - Retrieve all memberships for a user
- getOrganizationInvitations - Retrieve all invitations for a user
- verifyPassword - Verify the password of a user
- verifyTotp - Verify a TOTP or backup code for a user
- disableMfa - Disable a user's MFA methods
- deleteBackupCodes - Disable all user's Backup codes
- deletePasskey - Delete a user passkey
- deleteWeb3Wallet - Delete a user web3 wallet
- deleteTOTP - Delete all the user's TOTPs
- deleteExternalAccount - Delete External Account
- getInstanceOrganizationMemberships - Get a list of all organization memberships within an instance.
- list - List all waitlist entries
- create - Create a waitlist entry
- delete - Delete a pending waitlist entry
- invite - Invite a waitlist entry
- reject - Reject a waitlist entry
- createSvixApp - Create a Svix app
- deleteSvixApp - Delete a Svix app
- generateSvixAuthURL - Create a Svix Dashboard URL
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, you can provide a RetryConfig object through the retryConfig builder method:
package hello.world;
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialResponse;
import com.clerk.backend_api.utils.BackoffStrategy;
import com.clerk.backend_api.utils.RetryConfig;
import java.lang.Exception;
import java.util.concurrent.TimeUnit;
public class Application {
public static void main(String[] args) throws Exception {
Clerk sdk = Clerk.builder()
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.retryConfig(RetryConfig.builder()
.backoff(BackoffStrategy.builder()
.initialInterval(1L, TimeUnit.MILLISECONDS)
.maxInterval(50L, TimeUnit.MILLISECONDS)
.maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
.baseFactor(1.1)
.jitterFactor(0.15)
.retryConnectError(false)
.build())
.build())
.call();
// handle response
}
}If you'd like to override the default retry strategy for all operations that support retries, you can provide a configuration at SDK initialization:
package hello.world;
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialResponse;
import com.clerk.backend_api.utils.BackoffStrategy;
import com.clerk.backend_api.utils.RetryConfig;
import java.lang.Exception;
import java.util.concurrent.TimeUnit;
public class Application {
public static void main(String[] args) throws Exception {
Clerk sdk = Clerk.builder()
.retryConfig(RetryConfig.builder()
.backoff(BackoffStrategy.builder()
.initialInterval(1L, TimeUnit.MILLISECONDS)
.maxInterval(50L, TimeUnit.MILLISECONDS)
.maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
.baseFactor(1.1)
.jitterFactor(0.15)
.retryConnectError(false)
.build())
.build())
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.call();
// handle response
}
}Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.
ClerkError 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.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.errors.*;
import com.clerk.backend_api.models.operations.VerifyClientResponse;
import java.io.UncheckedIOException;
import java.lang.Exception;
import java.util.List;
import java.util.Optional;
public class Application {
public static void main(String[] args) throws ClerkErrors, Exception {
Clerk sdk = Clerk.builder()
.bearerAuth(System.getenv().getOrDefault("BEARER_AUTH", ""))
.build();
try {
VerifyClientResponse res = sdk.clients().verify()
.call();
if (res.client().isPresent()) {
// handle response
}
} catch (ClerkError ex) { // all SDK exceptions inherit from ClerkError
// 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 ClerkErrors) {
var e = (ClerkErrors) ex;
// Check error data fields
e.data().ifPresent(payload -> {
List<com.clerk.backend_api.models.components.ClerkError> errors = payload.errors();
Optional<Meta> meta = payload.meta();
});
}
// 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:
ClerkError: The base class for HTTP error responses.com.clerk.backend_api.models.errors.ClerkErrors: Request was not successful. *
Less common errors (17)
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 ClerkError:
com.clerk.backend_api.models.errors.CreateM2MTokenResponseBody: 400 Bad Request. Status code400. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.GetM2MTokensResponseBody: 400 Bad Request. Status code400. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.RevokeM2MTokenResponseBody: 400 Bad Request. Status code400. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.VerifyM2MTokenResponseBody: 400 Bad Request. Status code400. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.VerifyOAuthAccessTokenResponseBody: 400 Bad Request. Status code400. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.GetM2MTokensM2mResponseBody: 403 Forbidden. Status code403. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.GetM2MTokensM2mResponseResponseBody: 404 Not Found. Status code404. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.RevokeM2MTokenM2mResponseBody: 404 Not Found. Status code404. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.VerifyM2MTokenM2mResponseBody: 404 Not Found. Status code404. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.VerifyOAuthAccessTokenOauthAccessTokensResponseBody: 404 Not Found. Status code404. Applicable to 1 of 158 methods.*com.clerk.backend_api.models.errors.CreateM2MTokenM2mResponseBody: 409 Conflict. Status code409. Applicable to 1 of 158 methods.*
* Check the method documentation to see if the error is applicable.
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.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialResponse;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws Exception {
Clerk sdk = Clerk.builder()
.serverURL("https://api.clerk.com/v1")
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.call();
// 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.
The following example shows how to add a custom header and handle errors:
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.utils.HTTPClient;
import com.clerk.backend_api.utils.SpeakeasyHTTPClient;
import com.clerk.backend_api.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;
}
}
};
Clerk sdk = Clerk.builder()
.client(httpClient)
.build();
}
}Custom HTTP Client Configuration
You can also provide a completely custom HTTP client with your own configuration:
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.utils.HTTPClient;
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;
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());
}
};
Clerk sdk = Clerk.builder()
.client(customHttpClient)
.build();
}
}You can also enable debug logging on the default SpeakeasyHTTPClient:
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.utils.SpeakeasyHTTPClient;
public class Application {
public static void main(String[] args) {
SpeakeasyHTTPClient httpClient = new SpeakeasyHTTPClient();
httpClient.enableDebugLogging(true);
Clerk sdk = Clerk.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.
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!
