Skip to content

An async Java client for the OpenPolicyAgent REST API

License

Notifications You must be signed in to change notification settings

xenit-eu/opa-java-client

Repository files navigation

OpenPolicyAgent Java Client

Build Maven Central License

An asynchronous java client library for the OpenPolicyAgent REST API.

This repository has two components:

  • opa-async-java-client is the actual client for the OPA REST API
  • rego-java a library that models the Open Policy Agent policy language Rego

The design of the project is borrowed from Bisnode/opa-java-client, but uses an async programming model instead, which makes it suitable to be used in a reactive application stack.

This client library uses the JDK11+ HttpClient by default, but allows you to plug in your own http-client by providing an implementation for the OpaRestClient interface.

Installation

Prerequisites: Java 11 or higher

Using Gradle:

implementation "com.contentgrid.opa-java-client:opa-async-java-client:${version}"

Using Maven:

<dependency>
    <groupId>com.contentgrid.opa-java-client</groupId>
    <artifactId>opa-async-java-client</artifactId>
    <version>${version}</version>
</dependency>

Usage

Create an OpaClient instance:

OpaClient client = OpaClient.builder()
    .url("http://localhost:8181")
    .build();

Policies

List the ids of all policies:

client.listPolicies().thenAccept(response -> {
    var policies = response.getResult();
    policies.forEach(policy -> log.info("policy id: {}", policy.getId()));
});

Get a policy:

client.getPolicy("my-policy-id").thenAccept(response -> {
    AbstractSyntaxTree ast = response.getResult().getAst();
    // do something with the `ast`
});

Create a policy

client.upsertPolicy("policy_id", "content of the policy").join();

Data API

Query API

Compile API

Error handling

Error handling is not yet properly supported.

When the HTTP status code is 400 or higher, the returned CompletableFuture<T> will fail, with HttpStatusException as inner exception cause.

Example:

var result = client.upsertPolicy("my-policy", "invalid policy");

result.handle((response, ex) -> {
    if (ex != null) {
        if (ex.getCause() instanceof HttpStatusException) {
            if (((HttpStatusException) ex.getCause()).getStatusCode() == 400) {
                throw new IllegalArgumentException("policy content is not valid");
            }
        }
        throw RuntimeException(ex);
    }

    // happy path
    return response;
});