> ## Documentation Index
> Fetch the complete documentation index at: https://docs.open-metadata.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Java SDK Overview

> Enterprise Java integration client for OpenMetadata

# Java SDK

The OpenMetadata Java SDK provides a robust client library for Java applications to interact with the OpenMetadata API. It offers support for entity management, search, lineage, and authentication with a JWT token.

## Installation

### Maven

Add the OpenMetadata Java SDK dependency to your `pom.xml`:

```xml theme={null}
<dependency>
    <groupId>org.open-metadata</groupId>
    <artifactId>openmetadata-sdk</artifactId>
    <version>2.1.0.1</version>
</dependency>
```

### Gradle

Add the dependency to your `build.gradle`:

```gradle theme={null}
implementation 'org.open-metadata:openmetadata-sdk:2.1.0.1'
```

## Quick Start

### Basic Connection

```java theme={null}
import org.openmetadata.sdk.client.OpenMetadataClient;
import org.openmetadata.sdk.config.OpenMetadataConfig;
import org.openmetadata.sdk.network.HttpMethod;

// Create a client with a JWT token
OpenMetadataConfig config = OpenMetadataConfig.builder()
    .serverUrl("http://localhost:8585/api")
    .accessToken("your-jwt-token")
    .build();

OpenMetadataClient client = new OpenMetadataClient(config);

// Check the connection by reading the server version
String version = client.getHttpClient()
    .executeForString(HttpMethod.GET, "/v1/system/version", null);
System.out.println("Connected to OpenMetadata: " + version);
```

For more information about getting a token, see [Authentication](https://docs.open-metadata.org/v2.1.x/api-reference/authentication.md).

## Core Functionality

### Working with Entities

Every entity type has a service on the client, such as `client.databaseServices()`, `client.tables()`, and `client.users()`. These services offer methods such as `create`, `get`, `getByName`, `list`, `update`, `delete`, and `restore`.

#### Database Services

```java theme={null}
import org.openmetadata.schema.api.services.CreateDatabaseService;
import org.openmetadata.schema.api.services.DatabaseConnection;
import org.openmetadata.schema.entity.services.DatabaseService;
import org.openmetadata.schema.services.connections.database.MysqlConnection;
import org.openmetadata.sdk.models.ListParams;

// List database services
var services = client.databaseServices().list(new ListParams().setLimit(50));
System.out.println("Found " + services.getData().size() + " database services");

// Get specific service by name
DatabaseService service = client.databaseServices().getByName("mysql-prod");

// Create new database service
CreateDatabaseService createRequest = new CreateDatabaseService()
    .withName("new-mysql-service")
    .withServiceType(CreateDatabaseService.DatabaseServiceType.Mysql)
    .withDescription("Production MySQL database")
    .withConnection(new DatabaseConnection().withConfig(
        new MysqlConnection()
            .withHostPort("localhost:3306")
            .withUsername("openmetadata_user")));

DatabaseService newService = client.databaseServices().create(createRequest);
```

#### Tables

```java theme={null}
import java.util.List;
import org.openmetadata.schema.api.data.CreateTable;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.schema.type.Column;
import org.openmetadata.schema.type.ColumnDataType;
import org.openmetadata.sdk.models.ListParams;

// Get table by fully qualified name
Table table = client.tables().getByName("mysql-prod.employees.public.employees", "columns");
System.out.println("Table: " + table.getName());
System.out.println("Columns: " + table.getColumns().size());

// List tables in a schema with pagination
var tables = client.tables().list(
    new ListParams()
        .setLimit(10)
        .addFilter("databaseSchema", "mysql-prod.employees.public"));

// Create table
CreateTable createTable = new CreateTable()
    .withName("new_table")
    .withDatabaseSchema("mysql-prod.employees.public")
    .withColumns(List.of(
        new Column()
            .withName("id")
            .withDataType(ColumnDataType.BIGINT)
            .withDescription("Primary key"),
        new Column()
            .withName("name")
            .withDataType(ColumnDataType.VARCHAR)
            .withDataLength(255)
            .withDescription("Employee name")
    ));

Table newTable = client.tables().create(createTable);
```

### Entity Operations

#### CRUD Operations

```java theme={null}
import java.util.Map;
import java.util.UUID;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.schema.entity.services.DatabaseService;
import org.openmetadata.sdk.network.HttpMethod;

// Create or update a table
Table table = client.tables().createOrUpdate(createTable);

// Create or update a database service
DatabaseService service = client.getHttpClient().execute(
    HttpMethod.PUT, "/v1/services/databaseServices", createRequest, DatabaseService.class);

// Get by ID
UUID serviceId = service.getId();
DatabaseService sameService = client.databaseServices().get(serviceId);

// Delete
client.databaseServices().delete(serviceId.toString()); // soft delete
client.databaseServices().delete(serviceId.toString(), Map.of("hardDelete", "true")); // hard delete
```

#### Search and Filtering

```java theme={null}
import org.openmetadata.sdk.models.ListParams;

// Search tables. The response is the raw JSON from the server.
String results = client.search()
    .query("customer")
    .index("table_search_index")
    .size(50)
    .execute();
System.out.println(results);

// Advanced filtering
var customerTables = client.tables().list(
    new ListParams()
        .setLimit(100)
        .addFilter("database", "mysql-prod.ecommerce"));
```

## Advanced Features

### Authentication

The Java SDK authenticates with a JWT access token. When your token changes, create a new client with the new token:

```java theme={null}
import org.openmetadata.sdk.client.OpenMetadataClient;
import org.openmetadata.sdk.config.OpenMetadataConfig;

String newToken = "your-new-jwt-token";

OpenMetadataClient client = new OpenMetadataClient(
    OpenMetadataConfig.builder()
        .serverUrl("https://your-instance.com/api")
        .accessToken(newToken)
        .build());
```

### Error Handling

```java theme={null}
import org.openmetadata.sdk.exceptions.OpenMetadataException;

try {
    var table = client.tables().getByName("non-existent-table");
} catch (OpenMetadataException e) {
    switch (e.getStatusCode()) {
        case 404:
            System.out.println("Table not found");
            break;
        case 401:
            System.out.println("Authentication failed");
            break;
        case 403:
            System.out.println("Access denied");
            break;
        default:
            System.out.println("Error: " + e.getMessage());
    }
}
```

### Async Operations

The service methods are blocking. To run them in parallel, wrap them in a `CompletableFuture`:

```java theme={null}
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.schema.entity.services.DatabaseService;
import org.openmetadata.sdk.models.ListParams;

CompletableFuture<List<DatabaseService>> servicesFuture =
    CompletableFuture.supplyAsync(
        () -> client.databaseServices().list(new ListParams().setLimit(50)).getData());

CompletableFuture<Table> tableFuture =
    CompletableFuture.supplyAsync(
        () -> client.tables().getByName("mysql-prod.employees.public.employees", "columns"));

// Combine async operations
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(
    servicesFuture,
    tableFuture
).thenRun(() -> {
    try {
        List<DatabaseService> services = servicesFuture.get();
        Table table = tableFuture.get();

        System.out.println("Found " + services.size() + " services");
        System.out.println("Table columns: " + table.getColumns().size());
    } catch (Exception e) {
        e.printStackTrace();
    }
});
```

## Configuration Options

### Client Configuration

```java theme={null}
import org.openmetadata.sdk.client.OpenMetadataClient;
import org.openmetadata.sdk.config.OpenMetadataConfig;

OpenMetadataConfig config = OpenMetadataConfig.builder()
    .serverUrl("http://localhost:8585/api")
    .accessToken("your-jwt-token")
    .connectTimeout(30000)       // 30 seconds
    .readTimeout(60000)          // 60 seconds
    .writeTimeout(60000)         // 60 seconds
    .header("User-Agent", "MyApp/1.0") // Custom header on every request
    .build();

OpenMetadataClient client = new OpenMetadataClient(config);
```

## Common Use Cases

### Metadata Discovery

```java theme={null}
import java.util.ArrayList;
import java.util.List;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.sdk.models.ListParams;

// Discover all tables in a schema
String schemaName = "mysql-prod.employees.public";
List<Table> allTables = new ArrayList<>();

String after = null;
do {
    var params = new ListParams()
        .setLimit(100)
        .addFilter("databaseSchema", schemaName);
    if (after != null) {
        params.setAfter(after);
    }
    var batch = client.tables().list(params);
    allTables.addAll(batch.getData());
    after = batch.getPaging().getAfter();
} while (after != null);

System.out.println("Discovered " + allTables.size() + " tables");
```

### Bulk Operations

```java theme={null}
import java.util.List;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.sdk.models.ListParams;

// Bulk update table descriptions
List<Table> tables = client.tables()
    .list(new ListParams().setLimit(100).addFilter("databaseSchema", "mysql-prod.employees.public"))
    .getData();

for (Table table : tables) {
    if (table.getDescription() == null || table.getDescription().isEmpty()) {
        table.setDescription("Auto-generated description for " + table.getName());
        client.tables().update(table.getId().toString(), table);
    }
}
```

### Lineage Operations

```java theme={null}
// Get table lineage as JSON (1 hop upstream, 1 hop downstream)
String lineage = client.lineage().getLineageByName(
    "table",
    "mysql-prod.employees.public.employees",
    "1", // upstream depth
    "1"  // downstream depth
);

System.out.println(lineage);
```

For more information about the fluent API for lineage, see [Java SDK for Lineage](https://docs.open-metadata.org/v2.1.x/api-reference/sdk/java/lineage.md).

## Use the Client in Your Application

Create one `OpenMetadataClient` and share it across your application. If you use a framework such as Spring Boot, register the client as a singleton bean.

```java theme={null}
import org.openmetadata.sdk.client.OpenMetadataClient;
import org.openmetadata.sdk.config.OpenMetadataConfig;
import org.openmetadata.sdk.models.ListParams;

class MetadataService {

    private final OpenMetadataClient client;

    public MetadataService(String baseUrl, String jwtToken) {
        this.client = new OpenMetadataClient(
            OpenMetadataConfig.builder()
                .serverUrl(baseUrl)
                .accessToken(jwtToken)
                .build());
    }

    public java.util.List<org.openmetadata.schema.entity.data.Table> getTablesForSchema(String schemaFqn) {
        return client.tables()
            .list(new ListParams().setLimit(100).addFilter("databaseSchema", schemaFqn))
            .getData();
    }
}
```

## Best Practices

* **Reuse the client**: Create one client and share it instead of creating a new one per request.
* **Handle errors**: Catch `OpenMetadataException` and check the status code.
* **Protect authentication**: Keep your JWT token in a secret store, not in source code.
* **Use async operations**: Wrap calls in `CompletableFuture` for better performance in concurrent scenarios.
* **Handle pagination**: Always handle pagination for large datasets.
* **Cache entities**: Implement caching for frequently accessed entities.

## Performance Tips

* Create one client and reuse it.
* Cache frequently accessed metadata.
* Run independent calls in parallel with `CompletableFuture`.
* Specify only required fields when fetching entities.
* Use filters to narrow lists before you read them.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.