Skip to content

clerk/clerk-sdk-java

Repository files navigation

The most comprehensive User Management Platform



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.

SDK Installation

Getting started

JDK 11 or later is required.

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

Gradle:

implementation 'com.clerk:backend-api:0.2.0-beta'

Maven:

<dependency>
    <groupId>com.clerk</groupId>
    <artifactId>backend-api</artifactId>
    <version>0.2.0-beta</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.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.components.*;
import com.clerk.backend_api.models.components.Security;
import com.clerk.backend_api.models.operations.*;
import com.clerk.backend_api.utils.EventStream;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;
import static java.util.Map.entry;

public class Application {

    public static void main(String[] args) throws Exception {
        try {
            Clerk sdk = Clerk.builder()
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                .build();

            sdk.clients().list()
                .limit(10L)
                .offset(0L)
                .callAsStreamUnwrapped()
                .forEach(item -> {
                   // handle item
                });

        } catch (com.clerk.backend_api.models.errors.ClerkErrors e) {
            // handle exception
            throw e;
        } catch (Exception e) {
            // handle exception
            throw e;
        }

    }
}

Create Actor Tokens

This example shows how to create an actor token that can be used to impersonate the given user.

package hello.world;

import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.components.*;
import com.clerk.backend_api.models.components.Security;
import com.clerk.backend_api.models.operations.*;
import com.clerk.backend_api.utils.EventStream;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;
import static java.util.Map.entry;

public class Application {

    public static void main(String[] args) throws Exception {
        try {
            Clerk sdk = Clerk.builder()
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                .build();

            CreateActorTokenRequestBody req = CreateActorTokenRequestBody.builder()
                .userId("<value>")
                .actor(java.util.Map.ofEntries(
                        entry("sub", "user_2OEpKhcCN1Lat9NQ0G6puh7q5Rb")))
                .build();

            CreateActorTokenResponse res = sdk.actors().createToken()
                .request(req)
                .call();

            if (res.actorToken().isPresent()) {
                // handle response
            }
        } catch (com.clerk.backend_api.models.errors.ClerkErrors e) {
            // handle exception
            throw e;
        } catch (com.clerk.backend_api.models.errors.SDKError e) {
            // handle exception
            throw e;
        } catch (Exception e) {
            // handle exception
            throw e;
        }

    }
}

Available Resources and Operations

  • getJWKS - Retrieve the JSON Web Key Set of the instance
  • list - List all clients ⚠️ Deprecated
  • verify - Verify a client
  • get - Get a client
  • create - Create an email address
  • get - Retrieve an email address
  • delete - Delete an email address
  • update - Update an email address
  • create - Create a phone number
  • get - Retrieve a phone number
  • delete - Delete a phone number
  • update - Update a phone number
  • list - List all templates
  • get - Retrieve a template
  • upsert - Update a template for a given type and slug
  • revert - Revert a template
  • preview - Preview changes to a template
  • toggleDelivery - Toggle the delivery by Clerk for a template of a given type and slug
  • create - Create an invitation
  • list - List all invitations
  • revoke - Revokes an invitation
  • list - List all identifiers on the allow-list
  • create - Add identifier to the allow-list
  • delete - Delete identifier from allow-list
  • list - List all identifiers on the block-list
  • create - Add identifier to the block-list
  • delete - Delete identifier from block-list
  • list - List all instance domains
  • add - Add a domain
  • delete - Delete a satellite domain
  • update - Update a domain
  • list - List all templates
  • create - Create a JWT template
  • get - Retrieve a template
  • update - Update a JWT template
  • delete - Delete a Template
  • 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.
  • create - Create and send an organization invitation
  • list - Get a list of organization invitations
  • createBulk - 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
  • verifyDomain - 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
  • create - Create sign-in token
  • revoke - Revoke the given sign-in token
  • list - Get a list of OAuth applications for an instance
  • create - Create an OAuth application
  • get - Retrieve an OAuth application by ID
  • updateApplication - Update an OAuth application
  • delete - Delete an OAuth application
  • rotateSecret - Rotate the client secret of the given OAuth application
  • 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
  • create - Retrieve a new testing token

Pagination

Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the returned response object will have a next method that can be called to pull down the next group of results. The next function returns an Optional value, which isPresent until there are no more pages to be fetched.

Here's an example of one such pagination call:

package hello.world;

import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.components.*;
import com.clerk.backend_api.models.components.Security;
import com.clerk.backend_api.models.operations.*;
import com.clerk.backend_api.utils.EventStream;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;
import static java.util.Map.entry;

public class Application {

    public static void main(String[] args) throws Exception {
        try {
            Clerk sdk = Clerk.builder()
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                .build();

            sdk.clients().list()
                .limit(10L)
                .offset(0L)
                .callAsStreamUnwrapped()
                .forEach(item -> {
                   // handle item
                });

        } catch (com.clerk.backend_api.models.errors.ClerkErrors e) {
            // handle exception
            throw e;
        } catch (Exception e) {
            // handle exception
            throw e;
        }

    }
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an error. If Error objects are specified in your OpenAPI Spec, the SDK will throw the appropriate Exception type.

Error Object Status Code Content Type
models/errors/ClerkErrors 400,401,410,422 application/json
models/errors/SDKError 4xx-5xx */*

Example

package hello.world;

import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.components.*;
import com.clerk.backend_api.models.components.Security;
import com.clerk.backend_api.models.operations.*;
import com.clerk.backend_api.utils.EventStream;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;
import static java.util.Map.entry;

public class Application {

    public static void main(String[] args) throws Exception {
        try {
            Clerk sdk = Clerk.builder()
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                .build();

            sdk.clients().list()
                .limit(10L)
                .offset(0L)
                .callAsStreamUnwrapped()
                .forEach(item -> {
                   // handle item
                });

        } catch (com.clerk.backend_api.models.errors.ClerkErrors e) {
            // handle exception
            throw e;
        } catch (Exception e) {
            // handle exception
            throw e;
        }

    }
}

Server Selection

Select Server by Index

You can override the default server globally by passing a server index to the serverIndex 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 Variables
0 https://api.clerk.com/v1 None

Example

package hello.world;

import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.components.*;
import com.clerk.backend_api.models.operations.*;
import com.clerk.backend_api.utils.EventStream;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;
import static java.util.Map.entry;

public class Application {

    public static void main(String[] args) throws Exception {
        try {
            Clerk sdk = Clerk.builder()
                .serverIndex(0)
                .build();

            GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
                .frontendApi("<value>")
                .publishableKey("<value>")
                .call();

            // handle response
        } catch (com.clerk.backend_api.models.errors.SDKError e) {
            // handle exception
            throw e;
        } catch (Exception e) {
            // handle exception
            throw e;
        }

    }
}

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the 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.components.*;
import com.clerk.backend_api.models.operations.*;
import com.clerk.backend_api.utils.EventStream;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;
import static java.util.Map.entry;

public class Application {

    public static void main(String[] args) throws Exception {
        try {
            Clerk sdk = Clerk.builder()
                .serverURL("https://api.clerk.com/v1")
                .build();

            GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
                .frontendApi("<value>")
                .publishableKey("<value>")
                .call();

            // handle response
        } catch (com.clerk.backend_api.models.errors.SDKError e) {
            // handle exception
            throw e;
        } catch (Exception e) {
            // handle exception
            throw e;
        }

    }
}

Authentication

Per-Client Security Schemes

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.components.*;
import com.clerk.backend_api.models.operations.*;
import com.clerk.backend_api.utils.EventStream;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;
import static java.util.Map.entry;

public class Application {

    public static void main(String[] args) throws Exception {
        try {
            Clerk sdk = Clerk.builder()
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                .build();

            GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
                .frontendApi("<value>")
                .publishableKey("<value>")
                .call();

            // handle response
        } catch (com.clerk.backend_api.models.errors.SDKError e) {
            // handle exception
            throw e;
        } catch (Exception e) {
            // handle exception
            throw e;
        }

    }
}

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. 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!

SDK Created by Speakeasy