Repository navigation
Home
The SDK makes it easy to call Astra services using idiomatic Java APIs. On top of the SDK the repository provide tool like a Spring Boot starter and another samples helping you starting code with ASTRA and JAVA.

How do you want to connect?
| Options | Description |
|---|---|
| I don't want to create a schema. Just let me get started. | Use schemaless JSON Documents with the Document API |
| I want to start using my database now with APIs. | Use the REST API or GraphQL API to begin interacting with your database. |
| I have an application and want to use the DataStax drivers. | Use the CQL API leveraging DataStax drivers to manage database connections for your application. |
| I want to operate Astra, work with my instances. | Use the Devops API |
For any choice you will see that you only need to setup the class AstraClient with a builder and you are good to go.
The SDK has been build with the HttpClient provided in JDK. A You need JDK 11.0.9+ and a dependency management too as Maven or Gradle
It is a single library providing support for the 5 API(s) listed above.
Maven dependency in pom.xml
<dependency>
<groupId>com.datastax.astra</groupId>
<artifactId>astra-sdk-java</artifactId>
<version>${2021.1}</version>
</dependency>Gradle dependency in build.gradle
dependencies {
astra_sdk 'com.datastax.astra:astra-sdk-java:2021.1'
}You can use the class AstraClient to access any API (document, rest, cql, graphql, devops) . Not all parameters are needed, it depends on which API you want to use and if connection is created agains Astra or Stargate. With an important number of parameters a builder is provided.
Values are initialised with environment variables (if exist) full list here but you can define parameters programmatically as we do in the code snippet. Constants provided comply with expected format but are faked values. To locate values in the Astra user interface you can refer to this explanation.
Final word, we use object Person as our entity
AstraClient astraClient = AstraClient
.builder()
.astraDatabaseId("1111111-1111-1111-1111-111111111111") // Use in Rest,Doc,Devops,Cql APIs
.astraDatabaseRegion("europe-west1") // Use in Rest,Doc,Devops,Cql APIs
.username("astraUser") // Use in Rest,Doc,Cql APIs
.password("astraPassword") // Use in Rest,Doc,Cql APIs
.clientId("2222222-2222-2222-2222-22222222222") // Use in Devops only API
.clientName("cedric.lunven@datastax.com") // Use in Devops only API
.clientSecret("3333333-3333-3333-3333-333333333333") // Use in Devops only API
.build();
// DOCUMENT API
ApiDocumentClient apiDocClient = astraClient.apiDocument();
// DOC1. Create Namespace
if (!apiDocClient.namespace("five_min_namespace").exist()) {
// apiDocClient.namespace("five_min_namespace").create();
// We use the devops API with higher privileges
astraClient.apiDevops()
.createNamespace("1111111-1111-1111-1111-111111111111", "five_min_namespace");
}
// DOC2. Create a collection
if (!apiDocClient.namespace("five_min_namespace").collection("person").exist()) {
apiDocClient.namespace("five_min_namespace")
.collection("person")
.create();
}
// DOC3. Create a document Insert a Person and system generates id
String johnId = apiDocClient.namespace("five_min_namespace")
.collection("person")
.save(new Person("John", "Doe", 20, new Address("Paris", 75000)));
// DOC4. Upsert a document by providing id
apiDocClient.namespace("five_min_namespace")
.collection("person")
.document("saradoe")
.save(new Person("Sara", "Doe", 20, new Address("Paris", 75000)));
// DOC5. Find all (notice that everything is paged)
ResultListPage<Person> results = apiDocClient
.namespace("five_min_namespace")
.collection("person")
.findAll(Person.class);
// DOC6. Search: Find with a where Clause
ResultListPage<Person> results = collectionPerson.search(QueryDocument.builder()
.where("lastname").isEqualsTo("Doe").build(), Person.class);
// Devops API
ApiDevopsClient apiDevops = astraClient.apiDevops();
apiDevops.databases();
Optional<AstraDatabaseInfos > dbInfos = apiDevops.findDatabaseById("1111111-1111-1111-1111-111111111111");
// Rest API
ApiRestClient apiRest = astraClient.apiRest();
// Cql API (Drivers)
ApiCqlClient apiCql = astraClient.apiCql();Astra use the open source data gateway Stargate to expose REST, Document and GraphQL APIs, design is done to work with both. Depending on which API we want to use and if we use Astra or Stargate required parameters are not the same.
Parameters required in Astra for each API

Parameters required in Stargate for each API

Philosophy of the SDK is either to use AstraClientand fill the parameters you need to work with the API you need or instanciate the sub client you need.

Illustration to use either AstraClient facade or subclients.
// Use AstraClient
AstraClient astraClient = AstraClient.builder()
.astraDatabaseId(dbId)
.astraDatabaseRegion(dbRegion)
.username(dbUser)
.password(dbPasswd)
.build();
ApiDocumentClient apiDocument = astraClient.apiDocument();
// Create subclient direct
ApiDocumentClient apiDocClient = new ApiDocumentClient(dbId, dbRegion, dbUser, dbPasswd);📘 astraDatabaseId: It is the default identifier of a database hosted in Astra.
- Used only when working with Astra
- Mandatory to work with Doc, Rest or GraphQL APIS.
- Environment Variable lookup for initial value
ASTRA_DB_ID - Sample Use
AstraClient astraClient = AstraClient
.builder()
.astraDatabaseId("1111111-1111-1111-1111-111111111111");- Property found on the summary page
📘 astraDatabaseRegion: It is the default identifier of a database hosted in Astra
- Used only when working with Astra
- Mandatory to work with Doc, Rest or GraphQL APIS.
- Environment Variable lookup for initial value
ASTRA_DB_REGION - Sample Use
AstraClient astraClient = AstraClient
.builder()
.astraDatabaseRegion("europe-west-1");- Property found on the summary page
📘 baseUrl: It is the endpoint for Apis when working with Stargate
- Used only when working with Stargate
- Mandatory to work with Doc, Rest or GraphQL APIS.
- Environment Variable lookup for initial value
STARGATE_BASE_URL - Sample Use
AstraClient astraClient = AstraClient
.builder()
.baseUrl("htt[://localhost:8082/api");📘 Working with Astra
You rely on environment variables listed on the connect tab in ASTRA UI to initialize the client. We are here using an approach based on convention with name of environment pre-defined.
Expected environment variables
export ASTRA_DB_ID=<youdbId>
export ASTRA_DB_REGION=<youdbregion>
export ASTRA_DB_USERNAME=<username>
export ASTRA_DB_PASSWORD=<password>You might noticed than the ASTRA_DB_KEYSPACE here is not specifed as the client will allows you to work with DocApi, RestAPI and CQL and thus on all namespaces and keyspaces available on the target platform.
📘 Working with Stargate
If you are NOT using ASTRA but a StandAlone stargate the variables to define are slightly different. (if you define both Astra and Stargate keys - priority will go to Stargate.)
export USERNAME=<username>
export PASSWORD=<password>
export BASE_URL=<stargate_url>📘 Variables to configure
Same variables as the JavaScript SDK have been used for consitency. Some extra variable can still be provided to customize and specialize the client.
# Time to live of the authentication token
export TOKEN_TTL=300🛈 CODE
With environment defined as before initialization is as simple as:
AstraClient astraClient = AstraClient.builder().build();🖥️ Expected Output:
- Initializing Client: BaseUrl=https://e92195f2-159f-492e-9777-3dadda3ff1a3-europe-west1.apps.astra.datastax.com/api/rest, username=todouser,passwordLenght=13
- Successfully Authenticated, token will live for 300 second(s).
Modern java applications use fluent API approachs with a builder pattern in order to generate an immutable client.
To keep simply the AstraClientBuilder will work both for Astra and Stargate with different keys.
📘 Setup with Astra
AstraClient astraClient = AstraClient.builder()
.astraDatabaseId(<youdbId>")
.astraDatabaseRegion("<youdbregion>")
.username("<username>")
.password("<password>")
.tokenTtl(Duration.ofSeconds(300)) // optional default is 300s
.build()📘 Setup with Stargate
AstraClient stargateClient = AstraClient.builder()
.baseUrl("<stargate_url>")
.username("<username>")
.password("<password>")
.tokenTtl(Duration.ofSeconds(300)) // optional default is 300s
.build();
📘 Working with Astra
AstraClient astraClient = new AstraClient("<youdbId>", "<youdbregion>", "<username>", "<password>");
AstraClient astraClient = new AstraClient("<youdbId>", "<youdbregion>", "<username>", "<password>", Duration.ofSeconds(300));📘 Working with Stargate
AstraClient astraClient = new AstraClient("<baseUrl>", "<username>", "<password>");
AstraClient astraClient = new AstraClient("<baseUrl>", "<username>", "<password>", Duration.ofSeconds(300)); As the AstraClient can be initialized with a constructor you want to read values from configuration files like application.properties or application.yaml and inject them in the constructor.
A Spring Boot starter will look for the following key to initiate the client for you (see SPRING BOOT STARTER. You would also reuse environment variables defined before.
astra:
username: $(ASTRA_DB_ID:username}
password: <password>
dataBaseId: <dbId>
databaseRegion: <dbRegion>
baseUrl: <baseUrl>
tokenTtl: <tokenUrl>Sample Configuration Class
@Configuration
public class AstraConfiguration {
@Value("${astra.username}")
private String atraUsername;
@Value("${astra.password}")
private String atraPassword;
@Value("${astra.dataBaseId}")
private String dataBaseId;
@Value("${astra.databaseRegion}")
private String databaseRegion;
@Bean
protected Astraclient astraClient() {
return new AstraClient(dataBaseId, databaseRegion, atraUsername, atraPassword);
}
}To interact with Astra and Stargate you need to create an Authentication Token and provides it in the header for each of you query using key X-Cassandra-Token.
The work is done for you at the SDK level but not only. It will store it a renew it after a time to leave you setup. Before every class to the API the SDK check
the token. To create a token and as such validate your connection details you can do:
boolean isConnectionEstablished = astraClient.connect();As presented in the Astra Reference Documentation the Astra Document APIS is divided in 4 spaces: Authentications, Namespace, Keyspaces and Schemas.
Astra and Stargate bring great innovation by allowing Apache Cassandra to store Documents like a document-oriented noSQL database. To cope with Cassandra data model constraints the document shredding function has been used.
As a Java developer you want to work with objects (entities) and let the SDK interact with the API performing operations you need Create, Read, Update, Delete and search.
ARCHITECTURE PICS
-
Namespace: Namespace are simply keyspaces in Cassandra that will *only store documents you cannot mix documents and non document data. As such when working with
namespacewe know that we are working with the Document API.
*Astra Client is ready to work with the document API on namespace namespace_x
astraClient.namespace("namespace_x");- Collections: Collections are simply tables in Cassandra. Those tables are generated and managed for you but you need to know on which collection you are working for.
**✅ List available collections in a namespace. **
astraClient.namespace("namespace1") // select namespace1
.findAllCollections() // list collection names
.stream().forEach(System.out::println);; // Show values in console**✅ Check if a collection exist. **
boolean isAAAExist = astraClient.namespace("namespace1").existCollection("AAA");**✅ Create a new collection **
Collection name should be only Alpha Numeric characters.
astraClient.namespace("namespace1").createCollection("AAA");🏠 Home | Document | Rest | Native Drivers | GraphQL | gRPC | Astra Devops |