Skip to content

• Java


Select the API you want to connect to Astra with JAVA

Astra offers different Apis and interfaces. To know more about the ussage of each one check the pages dedicated to each one.

  • ASTRA DB (Stargate Apis)

              

1. Pre-requisites

  • Java Development Kit (JDK) 8+

Use reference documentation to install a Java Development Kit and validate your installation with

java --version
  • Apache Maven (3.8+)

The different samples and tutorials have been designed with Apache Maven.Use the reference documentation top install maven validate your installation with

mvn -version
  • Datastax Astra
Setup Actions

2. Native Cassandra Drivers

Driver reference documentation can be found HERE, this page is focused on connectivity with Astra DB only.

2.1 Cassandra Drivers 4.x

Version 4.x is recommended

Version 4 is major redesign of the internal architecture. As such, it is not binary compatible with previous versions. However, most of the concepts remain unchanged, and the new API will look very familiar to 2.x and 3.x users.

Import dependencies in your pom.xml
  • Any version 4.x should be compatible with Astra.

  • Update your pom.xml file with the latest version of the 4.x libraries: Maven Central

<!-- (REQUIRED) -->
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-core</artifactId>
<version>${latest4x}</version>
</dependency>

<!-- OPTIONAL -->
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-query-builder</artifactId>
<version>${latest4x}</version>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-mapper-runtime</artifactId>
<version>${latest4x}</version>
</dependency>
Standalone Code
  • CqlSession implements Closable. It should be a singleton in your application

  • Spring-Data 3.x+ relies on those Drivers 4x. If you define a CqlSession bean, it will use it.

import java.nio.file.Paths;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraDriver4x {

 static final String ASTRA_ZIP_FILE = "<path_to_secureConnectBundle.zip>";
 static final String ASTRA_USERNAME = "<provide_a_clientId>";
 static final String ASTRA_PASSWORD = "<provide_a_clientSecret>";
 static final String ASTRA_KEYSPACE = "<provide_your_keyspace>";

 public static void main(String[] args) {
   try (CqlSession cqlSession = CqlSession.builder()
     .withCloudSecureConnectBundle(Paths.get(ASTRA_ZIP_FILE))
     .withAuthCredentials(ASTRA_USERNAME, ASTRA_PASSWORD)
     .withKeyspace(ASTRA_KEYSPACE)
     .build()) {
      System.out.println("Hello keyspace {} !" + cqlSession.getKeyspace().get());
   }
 }

}
Resources

 Download This sample code

1.2 Cassandra Drivers 3.x

Version 4.x is recommended, it is unlikely that 3.x will get new updates except maintenance and CVE.

  • Please note that version 3.8+ is required to connect to Astra.
Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the 3.x libraries: Maven Central
<dependency>
  <groupId>com.datastax.cassandra</groupId>
  <artifactId>cassandra-driver-core</artifactId>
  <version>${latest3x}</version>
</dependency>
Standalone Code
import java.io.File;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;

public class AstraDriver3x {

  // Define inputs
  static final String ASTRA_ZIP_FILE = "<path_to_secureConnectBundle.zip>";
  static final String ASTRA_USERNAME = "<provide_a_clientId>";
  static final String ASTRA_PASSWORD = "<provide_a_clientSecret>";
  static final String ASTRA_KEYSPACE = "<provide_your_keyspace>";

  public static void main(String[] args) {
    try(Cluster cluster = Cluster.builder()
      .withCloudSecureConnectBundle(new File(ASTRA_ZIP_FILE))
      .withCredentials(ASTRA_USERNAME, ASTRA_PASSWORD)
      .build() ) {
        Session session = cluster.connect(ASTRA_KEYSPACE);
        System.out.println("Hello keyspace " + session.getLoggedKeyspace());
    }
  }

}
Resources

 Download Driver 3x Sample

1.3 Astra SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Standalone Code
import java.io.File;
import com.datastax.astra.sdk.AstraClient;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraSdk {

  // Define inputs
  static final String ASTRA_DB_TOKEN  = "<provide_a_clientSecret>";
  static final String ASTRA_DB_ID     = "<provide_your_database_id>";
  static final String ASTRA_DB_REGION = "<provide_your_database_region>";
  static final String ASTRA_KEYSPACE  = "<provide_your_keyspace>";

  // Init Astra Client
  public static void main(String[] args) {
      try(AstraClient cli = AstraClient.builder()
        .withToken(ASTRA_DB_TOKEN)
        .withDatabaseId(ASTRA_DB_ID)
        .withDatabaseRegion(ASTRA_DB_REGION)
        .withCqlKeyspace(ASTRA_DB_KEYSPACE)
        .enableCql()
        .build()) {
          System.out.println("CqlVersion:" + astraClient.cqlSession()
                    .execute("SELECT cql_version from system.local")
                    .one().getString("cql_version"));
      }
    }
}
Resources

 Download SDK Sample

3. Api Rest

⚠️ We recommend to use version V2 (with V2 in the URL) as it covers more features and the V1 would be deprecated sooner.

To know more regarding this interface specially you can have a look to dedicated section of the wiki or reference Stargate Rest Api Quick Start Guide.

3.1 Http Client

You need an HTTP Client to use the Rest API. There are a lot of clients in the Java languages like HttpURLConnection, HttpClient introduced in Java 11, Apache HTTPClient, OkHttpClient, Jetty HttpClient. A comparison is provided is this blogpost to make your choice. In this tutorial, we will use the Apache HttpClient, which is included in the SDK. You should adapt the code depending on the framework you have chosen.

Import dependencies in your pom.xml
<dependency>
  <groupId>org.apache.httpcomponents.client5</groupId>
  <artifactId>httpclient5</artifactId>
  <version>5.1.3</version>
</dependency>
Standalone Code
import java.io.File;
public class AstraRestApiHttpClient {

    static final String ASTRA_TOKEN       = "<change_with_your_token>";
    static final String ASTRA_DB_ID       = "<change_with_your_database_identifier>";
    static final String ASTRA_DB_REGION   = "<change_with_your_database_region>";
    static final String ASTRA_DB_KEYSPACE = "<change_with_your_keyspace>";

    public static void main(String[] args) throws Exception {

        String apiRestEndpoint = new StringBuilder("https://")
                .append(ASTRA_DB_ID).append("-")
                .append(ASTRA_DB_REGION)
                .append(".apps.astra.datastax.com/api/rest")
                .toString();
        System.out.println("Rest Endpoint is " + apiRestEndpoint);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // Work with HTTP CLIENT
            listKeyspaces(httpClient, apiRestEndpoint);
            createTable(httpClient, apiRestEndpoint);
        }
    }
}
  • Operations
List Keyspaces

  • Code
private static void listKeyspaces(CloseableHttpClient httpClient, String apiRestEndpoint)
throws Exception {
        // Build Request
        HttpGet listKeyspacesReq = new HttpGet(apiRestEndpoint + "/v2/schemas/keyspaces");
        listKeyspacesReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);

        // Execute Request
        try(CloseableHttpResponse res = httpClient.execute(listKeyspacesReq)) {
        if (200 == res.getCode()) {
        logger.info("[OK] Keyspaces list retrieved");
        logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
}
Creating a table

  • Sample JSON payload createTableJson.
{
  "name": "users",
  "columnDefinitions": [
    {  "name": "firstname", "typeDefinition": "text" },
    {  "name": "lastname",  "typeDefinition": "text" },
    {  "name": "email",     "typeDefinition": "text" },
    {  "name": "color",     "typeDefinition": "text" }
  ],
  "primaryKey": { 
    "partitionKey": ["firstname"],
    "clusteringKey": ["lastname"]
  },
  "tableOptions": {
    "defaultTimeToLive": 0,
    "clusteringExpression": [{ "column": "lastname", "order": "ASC" }]
  }
}
  • Creating the http request using that payload
private static void createTable(CloseableHttpClient httpClient, String apiRestEndpoint)
throws Exception {
  HttpPost createTableReq = new HttpPost(apiRestEndpoint
      + "/v2/schemas/keyspaces/" + ASTRA_DB_KEYSPACE + "/tables");
  createTableReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);
  String createTableJson = "{...JSON.....}";
  createTableReq.setEntity(new StringEntity(createTableJson, ContentType.APPLICATION_JSON));

  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(createTableReq)) {
    if (201 == res.getCode()) {
      logger.info("[OK] Table Created (if needed)");
      logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
    }
  }
}
Insert a new Row

private static void insertRow(CloseableHttpClient httpClient, String apiRestEndpoint)
throws Exception {
  HttpPost insertCedrick = new HttpPost(apiRestEndpoint + "/v2/keyspaces/"
  + ASTRA_DB_KEYSPACE + "/users" );
  insertCedrick.addHeader("X-Cassandra-Token", ASTRA_TOKEN);
  insertCedrick.setEntity(new StringEntity("{"
    + " \"firstname\": \"Cedrick\","
    + " \"lastname\" : \"Lunven\","
    + " \"email\"    : \"c.lunven@gmail.com\","
    + " \"color\"    : \"blue\" }", ContentType.APPLICATION_JSON));

  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(insertCedrick)) {
    if (201 == res.getCode()) {
      logger.info("[OK] Row inserted");
      logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
    }
  }
}
Retrieve a row

private static void retrieveRow(CloseableHttpClient httpClient, String apiRestEndpoint)
throws Exception {

  // Build Request
  HttpGet rowReq = new HttpGet(apiRestEndpoint + "/v2/keyspaces/"
    + ASTRA_DB_KEYSPACE + "/users/Cedrick/Lunven" );
  rowReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);

  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(rowReq)) {
    if (200 == res.getCode()) {
      String payload =  EntityUtils.toString(res.getEntity());
      logger.info("[OK] Row retrieved");
      logger.info("Row retrieved : {}", payload);
    }
  }
}
Resources

 Download REST HTTP CLIENT

3.2 Astra SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Standalone Code
import java.io.File;
import com.datastax.astra.sdk.AstraClient;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraSdk {

  // Define inputs
  static final String ASTRA_DB_TOKEN  = "<provide_a_clientSecret>";
  static final String ASTRA_DB_ID     = "<provide_your_database_id>";
  static final String ASTRA_DB_REGION = "<provide_your_database_region>";
  static final String ASTRA_KEYSPACE  = "<provide_your_keyspace>";

  // Init Astra Client
  public static void main(String[] args) {
      try(AstraClient cli = AstraClient.builder()
        .withToken(ASTRA_DB_TOKEN)
        .withDatabaseId(ASTRA_DB_ID)
        .withDatabaseRegion(ASTRA_DB_REGION)
        .withCqlKeyspace(ASTRA_DB_KEYSPACE)
        .build()) {
          System.out.println("+ List of Keyspaces: " + 
            astraClient.apiStargateData()
                       .keyspaceNames()
                       .collect(Collectors.toList()));
      }
  }
}
Resources

 Download SDK Sample

4. Api Document

The Document API is an HTTP REST API and part of the open source Stargate.io. The idea is to provide an abstraction on top of Apache Cassandra™ to allow document-oriented access patterns. To get familiar with it you can access documentation and sandbox here

4.1 Http Client

Import dependencies in your pom.xml
<dependency>
  <groupId>org.apache.httpcomponents.client5</groupId>
  <artifactId>httpclient5</artifactId>
  <version>5.1.3</version>
</dependency>
Standalone Code
static final String ASTRA_TOKEN       = "change_me";
static final String ASTRA_DB_ID       = "change_me";
static final String ASTRA_DB_REGION   = "change_me";
static final String ASTRA_DB_KEYSPACE = "change_me";
static  Logger logger = LoggerFactory.getLogger(AstraDocApiHttpClient.class);

public static void main(String[] args) throws Exception {
   try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

        // Build Request
        String apiRestEndpoint = new StringBuilder("https://")
            .append(ASTRA_DB_ID).append("-")
            .append(ASTRA_DB_REGION)
            .append(".apps.astra.datastax.com/api/rest")
            .toString();
        HttpGet req = new HttpGet(apiRestEndpoint + "/v2/schemas/namespaces");
        req.addHeader("X-Cassandra-Token", ASTRA_TOKEN);

        // Execute Request
        try(CloseableHttpResponse res = httpClient.execute(req)) {
          if (200 == res.getCode()) {
            logger.info("[OK] Namespaces list retrieved");
            logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
          }
        }
   }
}
Resources

 Download SDK Sample

4.2 Astra SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Standalone Code
import java.io.File;
import com.datastax.astra.sdk.AstraClient;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraSdk {

  // Define inputs
  static final String ASTRA_DB_TOKEN  = "<provide_a_clientSecret>";
  static final String ASTRA_DB_ID     = "<provide_your_database_id>";
  static final String ASTRA_DB_REGION = "<provide_your_database_region>";
  static final String ASTRA_KEYSPACE  = "<provide_your_keyspace>";

  // Init Astra Client
  public static void main(String[] args) {
      try(AstraClient cli = AstraClient.builder()
        .withToken(ASTRA_DB_TOKEN)
        .withDatabaseId(ASTRA_DB_ID)
        .withDatabaseRegion(ASTRA_DB_REGION)
        .withCqlKeyspace(ASTRA_DB_KEYSPACE)
        .build()) {
          System.out.println("+ List of Keyspaces: " + 
            astraClient.apiStargateDocument()
                       .namespaceNames()
                       .collect(Collectors.toList()));
      }
  }
}
Resources

 Download SDK Sample

5 Api GraphQL

5.1 Astra SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Standalone Code
import java.io.File;
import com.datastax.astra.sdk.AstraClient;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraSdk {

  // Define inputs
  static final String ASTRA_DB_TOKEN  = "<provide_a_clientSecret>";
  static final String ASTRA_DB_ID     = "<provide_your_database_id>";
  static final String ASTRA_DB_REGION = "<provide_your_database_region>";
  static final String ASTRA_KEYSPACE  = "<provide_your_keyspace>";

  // Init Astra Client
  public static void main(String[] args) {
      try(AstraClient cli = AstraClient.builder()
        .withToken(ASTRA_DB_TOKEN)
        .withDatabaseId(ASTRA_DB_ID)
        .withDatabaseRegion(ASTRA_DB_REGION)
        .withCqlKeyspace(ASTRA_DB_KEYSPACE)
        .build()) {
           System.out.println("+ Keyspaces (graphQL) : " + astraClient
              .apiStargateGraphQL()
              .cqlSchema()
              .keyspaces());
      }
  }
}
Resources

 Download SDK Sample

6. Api gRPC

6.1 Grpc Client

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
   <dependency>
      <groupId>io.stargate.grpc</groupId>
      <artifactId>grpc-proto</artifactId>
      <version>${latest-grpc-stargate}</version>
  </dependency>
  <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-netty-shaded</artifactId>
  </dependency>
</dependencies>
Standalone Code
  public class GrpcClient {

    // Define inputs
    static final String ASTRA_DB_TOKEN  = "<provide_a_clientSecret>";
    static final String ASTRA_DB_ID     = "<provide_your_database_id>";
    static final String ASTRA_DB_REGION = "<provide_your_database_region>";

    // Open Grpc communicatino 
    ManagedChannel channel = ManagedChannelBuilder
      .forAddress(ASTRA_DB_ID + "-" + ASTRA_DB_REGION + ".apps.astra.datastax.com", 443)
      .useTransportSecurity()
      .build();

    // use Grpc Stub generated from .proto as a client
    StargateGrpc.StargateBlockingStub cloudNativeClient = StargateGrpc
          .newBlockingStub(channel)
          .withCallCredentials(new StargateBearerToken(ASTRA_DB_TOKEN))
          .withDeadlineAfter(5, TimeUnit.SECONDS);

  // create Query
  String cqlQuery = "SELECT data_center from system.local";

  // Execute the Query
  Response res = cloudNativeClient.executeQuery(QueryOuterClass
                  .Query.newBuilder().setCql(cqlQuery).build());

  // Accessing Row result
  QueryOuterClass.Row row = res.getResultSet().getRowsList().get(0);

  // Access the single value
  String datacenterName = row.getValues(0).getString();
  System.out.println("You are connected to '%s'".formatted(datacenterName));

6.2 Astra SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Standalone Code
// Initialize Astra Client with token and database identifiers
        try(AstraClient astraClient = AstraClient.builder()
                .withDatabaseId(ASTRA_DB_ID)
                .withDatabaseRegion(ASTRA_DB_REGION)
                .withToken(ASTRA_DB_TOKEN)
                .enableGrpc()
                .build()) {

            // Accessin the gRPC API
            ApiGrpcClient cloudNativeClient = astraClient.apiStargateGrpc();

            // Reuse cql query
            String cqlQuery = "SELECT data_center from system.local";

            // Executing Query
            ResultSetGrpc rs = cloudNativeClient.execute(cqlQuery);

            // Accessing reulst
            String datacenterName = rs.one().getString("data_center");
            System.out.println("You are connected to '%s'".formatted(datacenterName));

            // Validating the test
            Assertions.assertNotNull(datacenterName);
        }

Last update: 2023-01-18