Java Client Library

On this page

The Java client library integrates FusionAuth with your Java application. The source code is in the Java client GitHub repository.

Install#

Add the Maven dependency to your project:

<dependency>
  <groupId>io.fusionauth</groupId>
  <artifactId>fusionauth-java-client</artifactId>
  <version>${fusionauth.version}</version>
</dependency>

Use the library version that matches the version of FusionAuth you run. To see all available versions, search for the fusionauth-java-client artifact on Maven Central.

Consume the ClientResponse#

The Java client offers two styles of use. The first style returns a ClientResponse object. The object contains everything that happened while the client communicated with the FusionAuth server. When the communication hits a network issue, ClientResponse.exception can contain an IOException.

The following code assumes FusionAuth runs at http://localhost:9011 and uses the API key {props.api_key}. Replace the API key with your own. When FusionAuth doesn't run locally, replace the host URL too.

The following example uses the retrieveUserByEmail method to retrieve a User by email address:

import com.inversoft.error.Errors;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.User;
import io.fusionauth.domain.api.UserResponse;
import com.inversoft.rest.ClientResponse;
public class Example {
  private final FusionAuthClient client;

  public Example() {
    client = new FusionAuthClient("6b87a398-39f2-4692-927b-13188a81a9a3", "http://localhost:9011");
  }

  public User getUserByEmail(String email) {
    ClientResponse<UserResponse, Errors> response = client.retrieveUserByEmail(email);
    if (response.wasSuccessful()) {
      return response.successResponse.user;
    } else if (response.errorResponse != null) {
      // error handling
      Errors errors = response.errorResponse;
    } else if (response.exception != null) {
      // exception handling
      Exception exception = response.exception;
    }

    return null;
  }
}

Use the Lambda Delegate#

The second style uses the Lambda delegate. The delegate handles exceptions, so you can write code for the happy path. The following example repeats the previous example with the Lambda delegate:

import com.inversoft.error.Errors;
import io.fusionauth.client.LambdaDelegate;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.User;
import com.inversoft.rest.ClientResponse;
public class Example {
  private final String apiKey = "6b87a398-39f2-4692-927b-13188a81a9a3";

  private final String fusionauthURL = "http://localhost:9011";

  private final FusionAuthClient client;

  private final LambdaDelegate delegate;

  public Example(String apiKey, String fusionauthURL) {
    this.client = new FusionAuthClient(apiKey, fusionauthURL);
    this.delegate = new LambdaDelegate(this.client, (r) -> r.successResponse, this::handleError);
  }

  public User getUserByEmail(String email) {
    return delegate.execute(c -> c.retrieveUserByEmail("user@example.com")).user;
  }

  private <T, U> void handleError(ClientResponse<T, U> clientResponse) {
    if (clientResponse.exception != null) {
      // handle the exception
      ...
    } else if (clientResponse.errorResponse != null && clientResponse.errorResponse instanceof Errors) {
      // handle errors
      ...
    }
  }
}

The Lambda delegate needs less code to handle the success response, and you can reuse the error handling code.

Usage Suggestions#

Choose a Use Case#

Client libraries wrap the REST API. You can use a client library for two tasks.

The main task is calling the FusionAuth APIs from code. You get auto-completion and typed objects, which helps when you script configuration, automate common tasks, or copy existing Applications and Groups. The API documentation lists the JSON structure of every request and which fields each call requires. When you need the details, read the API documentation and the library source code.

The secondary task is exchanging an authorization code for tokens in the Authorization Code grant. For this task, use an OAuth library for your language instead. For a list of libraries, see the community curated list.

Client libraries don't provide higher level functionality such as token management. To request that functionality, comment on or upvote the open issue.

When a client library doesn't fit your needs, call the REST API directly.

Requests and Responses#

Each library maps a request object to the JSON that the matching API method requires. Depending on the API call, the request object is a set of string parameters or a complex object. When you use a language without static typing, read the API documentation for the operation to learn the expected fields.

Each library returns a response object with these fields:

  • A status that matches the HTTP status code from the API. The status is -1 when no HTTP request succeeded.
  • A JSON success object when the call succeeds.
  • A JSON error object with a message when the status is 4xx or 5xx.
  • An exception object when the library sent no request or the server returned no usable response.

Use Separate Clients for API Key Scopes#

When a script calls endpoints with different API key scopes, create one client instance per scope. For example, Entities accept a tenant-scoped API key, but Entity Types and Lambdas require a global API key.

Follow these rules when your library lets you set a Tenant Id on the client instance:

  • Set the Tenant Id on the tenant-scoped client only.
  • Don't change the Tenant Id on a shared client between calls.
  • Don't send a tenant header to a global-only endpoint. The endpoint fails with a 401.

PATCH Requests#

Available since 1.14.0

PATCH operations modify only parts of an object in FusionAuth. The Java client library is statically typed, so the library doesn't use strongly typed objects for a PATCH request. Instead, you pass a hash, dictionary, or map of key value pairs. Build a multi-level dictionary that creates JSON with nested keys. Otherwise the PATCH request fails.

For example, to change only the name of an Application with PATCH, send this JSON:

Example PATCH Application JSON
{
  "application": {
     "name": "hooli-bought-us"
   }
}

A typed request object serializes with empty arrays and other default values. Those values change the object in ways you don't expect. Nested key value pairs avoid the problem.

This limitation comes from the current implementation of the Java client library and FusionAuth PATCH support. To support typed objects, the domain objects would need no default values, and the serializer would need to omit empty objects, empty arrays, and other empty values.

To use typed objects today, retrieve the object, modify the object in memory, and then update the object. This sequence works the same as a single PATCH operation.

For more information about future support, see the open issue to handle PATCH requests with more nuance. The issue may add options for configuring a JSON serializer to allow typed domain objects with PATCH.

Example Apps#

  • Java Android quickstart - Java Android quickstart tutorial showing how to integrate FusionAuth with a Java Android mobile application and AppAuth
  • Java JWT - JWT creation and decoding examples with the fusionauth-jwt library
  • Java Spring Boot API quickstart - Java Spring Boot API quickstart tutorial showing how to integrate FusionAuth with a Java Spring Boot API
  • Java Spring Boot quickstart - Java Spring Boot quickstart tutorial showing how to integrate FusionAuth with a Java Spring Boot application
  • Kotlin Android quickstart - Kotlin Android quickstart tutorial showing how to integrate FusionAuth with a Kotlin Android mobile application
  • SCIM Client - An example SCIM client using FusionAuth as the SCIM server
  • User and application management - Using the FusionAuth Java client library to add and remove users and applications
  • Webhook Lambda Function - Stores FusionAuth webhook events to S3 using the CDK to manage infra

Update Policy#

FusionAuth releases new versions of the SDKs and client libraries to track the FusionAuth API. SDKs and client libraries may also receive bug fixes, security patches, tests, code samples, and documentation changes.

These releases may update dependencies, language engines, and operating systems, because FusionAuth follows the deprecation and sunsetting policies of the underlying technologies. When the maintainer deprecates a language, framework, or operating system, FusionAuth deprecates the SDKs and client libraries that depend on the technology. FusionAuth then updates the SDKs and client libraries to use a newer version.

For more information, see Update a Client Library.