Get started with the Data API

You can interact with the Data API through clients or directly through HTTP.

Install a client

Use a package manager to install the client library for your preferred language.

  • Python

  • TypeScript

  • Java

  • curl

Install the Python client with pip:

  1. Verify that pip is version 23.0 or later:

    pip --version
  2. If needed, upgrade pip:

    python -m pip install --upgrade pip
  3. Install the astrapy package Latest release. You must have Python 3.8 or later.

    pip install astrapy

Install the TypeScript client:

  1. Verify that Node is version 18 or later:

    node --version
  2. Install astra-db-ts Latest release with your preferred package manager:

    • npm

    • Yarn

    • pnpm

    npm install @datastax/astra-db-ts
    yarn add @datastax/astra-db-ts
    pnpm add @datastax/astra-db-ts

Install the Java client with Maven or Gradle.

  • Maven

  • Gradle

  1. Install Java 11 or later and Maven 3.9 or later.

  2. Create a pom.xml file in the root of your project, and then replace VERSION with the latest version of astra-db-java Maven Central.

    pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                                 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.example</groupId>
      <artifactId>test-java-client</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <!-- The Java client -->
      <dependencies>
        <dependency>
          <groupId>com.datastax.astra</groupId>
          <artifactId>astra-db-java</artifactId>
          <version>VERSION</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
              <executable>java</executable>
              <mainClass>com.example.Quickstart</mainClass>
            </configuration>
            <executions>
              <execution>
                <goals>
                  <goal>java</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
              <source>11</source>
              <target>11</target>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
  1. Install Gradle and Java 11 or later.

  2. Create a build.gradle file in the root of your project:

    build.gradle
    plugins {
        id 'java'
        id 'application'
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.datastax.astra:astra-db-java:1.+'
    }
    
    application {
        mainClassName = 'com.example.Quickstart'
    }

To interact with the Data API directly through HTTP, install a tool to handle API calls, such as curl.

Upgrade a client

When a new client version is released, upgrade your client to get the latest features, improvements, and bug fixes. For information about major changes in specific client versions, see Compare Data API client versions.

  • Python

  • TypeScript

  • Java

  • curl

# verbose
pip install astrapy --upgrade

# shorthand
pip install -U astrapy

Reinstall the TypeScript client at the latest version.

For the TypeScript client, DataStax recommends reinstallation instead of upgrade and update commands, such as npm update @datastax/astra-db-ts, that install the latest version allowed by your package.json. If your package.json pins a version that is earlier than the actual latest version, then upgrade and update won’t install the actual latest version.

# npm
npm install @datastax/astra-db-ts@latest

# Yarn
yarn add @datastax/astra-db-ts@latest

# pnpm
pnpm add @datastax/astra-db-ts@latest

To upgrade your Java client, modify the astra-db-java version in your project’s build.gradle or pom.xml.

Because Astra DB is a cloud service, the Data API itself always runs the latest production version.

For information about upgrading a utility like curl, see the documentation for that tool.

Set environment variables

The Data API requires an application token and your database’s API endpoint for most operations. Store these values in environment variables to simplify reuse in your scripts:

  1. Generate an application token with the Database Administrator role, and then get your database’s API endpoint in the form of https://DATABASE_ID-REGION.apps.astra.datastax.com. For more information, see Generate an application token for a database.

  2. Set environment variables for your token and API endpoint:

    • Linux or macOS

    • Windows

    export ASTRA_DB_API_ENDPOINT=API_ENDPOINT
    export ASTRA_DB_APPLICATION_TOKEN=TOKEN
    set ASTRA_DB_API_ENDPOINT=API_ENDPOINT
    set ASTRA_DB_APPLICATION_TOKEN=TOKEN

Instantiate a client object

When you create apps using the Data API clients for Python, TypeScript, and Java, your main entry point is the DataAPIClient object.

When you interact with the Data API directly through HTTP, you provide a database API endpoint URL that specifies the database that you want to interact with, and you provide an application token with sufficient permission to perform the requested commands.

However, client objects aren’t specific to a database. Therefore, when you instantiate a client, you only provide a token that has adequate permissions to perform the desired operations on the target databases.

  • Python

  • TypeScript

  • Java

  • curl

For more information, see the Client reference.

client = DataAPIClient("TOKEN")

Parameters:

Name Type Summary

token

str

An application token for a database, in the form of AstraCS:…​.

Returns:

DataAPIClient: An instance of the client class.

Example response
DataAPIClient("AstraCS:aAbB...")

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
database0 = client.get_database("DB_API_ENDPOINT")
collection0 = database0.create_collection("movies", dimension=5)
collection0.insert_one({
    "title": "The Title",
    "$vector": [0.1, 0.3, -0.7, 0.9, -0.1],
})
admin = client.get_admin()
admin1 = client.get_admin(token=more_powerful_token_override)
database_iterator = admin.list_databases()

For more information, see the Client reference.

const client = new DataAPIClient('TOKEN');

Parameters:

Name Type Summary

token?

string

An application token for a database. Tokens are prefixed with AstraCS:.

You can omit this and, instead, pass it with client.db() or client.admin() through the token parameter.

options?

DataAPIClientOptions

The options to use for the client, including defaults.

Name Type Summary

environment?

DataAPIEnvironment

Sets the Data API backend to use (for example, dse, hcd, astra). The default is astra.

Most operations are the same between backends. Authentication and available administration operations can differ. For more information, see the astra-db-ts README.

httpOptions?

DataAPIHttpOptions

Options related to the API requests the client makes.

dbOptions?

DbSpawnOptions

Allows default options for when spawning a Db instance.

adminOptions?

AdminSpawnOptions

Allows default options for when spawning some Admin instance.

Http options (DataAPIHttpOptions):

The DataAPIHttpOptions type is a discriminated union on the client field. There are four available behaviors for the client field:

  • httpOptions not set: Use fetch-h2 if available or fall back to fetch.

  • client: 'default' or unset: Use fetch-h2 if available or throw an error.

  • client: 'fetch': Only use the native fetch API.

  • client: 'custom': Pass a custom Fetcher implementation to the client.

fetch-h2 is generally available by default on node runtimes only. On other runtimes, you might need to use the native fetch API or, if your code is minified, pass in the fetch-h2 module manually.

For more information on http clients, see the astra-db-ts README and the Client reference.

Returns:

DataAPIClient - An instance of the client class.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts';

const client = new DataAPIClient('TOKEN');

const db1 = client.db('DB_API_ENDPOINT');

(async function () {
  const coll = await db1.createCollection('movies');

  const admin1 = client.admin();
  const admin2 = client.admin({ adminToken: 'STRONGER_TOKEN' });

  console.log(await coll.insertOne({ name: 'Airplane!' }));
  console.log(await admin1.listDatabases());
})();

For information on setting up commands monitoring, see the astra-db-ts README.

// Default Initialization
DataAPIClient client = new DataAPIClient("TOKEN");

// Overriding default settings
DataAPIClient client = new DataAPIClient("TOKEN", DataAPIOptions.builder()
  .withHttpConnectTimeout(20)
  .withHttpRequestTimeout(20)
  .build());

Parameters:

Name Type Summary

token

String

An application token for a database. Tokens are prefixed with AstraCS:.

options

DataAPIOptions

A class wrapping the advanced configuration of the client, such as as HttpClient settings like timeouts.

Returns:

DataAPIClient - An instance of the client class.

Example:

package com.datastax.astra.client;

import java.util.UUID;

public class Connecting {
    public static void main(String[] args) {
        // Preferred Access with DataAPIClient (default options)
        DataAPIClient client = new DataAPIClient("TOKEN");

        // Overriding the default options
        DataAPIClient client1 = new DataAPIClient("TOKEN", DataAPIOptions
                .builder()
                .withMaxTimeMS(10)
                .withHttpConnectTimeout(10)
                .build());

        // Access the Database from its endpoint
        Database db1 = client1.getDatabase("API_ENDPOINT");
        Database db2 = client1.getDatabase("API_ENDPOINT", "KEYSPACE");

        // Access the Database from its endpoint
        UUID databaseId = UUID.fromString("f5abf92f-ff66-48a0-bbc2-d240bc25dc1f");
        Database db3 = client.getDatabase(databaseId);
        Database db4 = client.getDatabase(databaseId, "KEYSPACE");
        Database db5 = client.getDatabase(databaseId, "KEYSPACE", "us-east-2");

        db5.useNamespace("yet_another");

    }
}

This step isn’t necessary when interacting with the Data API directly through HTTP.

Connect to a database

You must connect to a database before you can work with the collections and documents in it. This operation is the basis of Data API calls. It is one of the first operations you need in any client script, and you’ll encounter these commands at the beginning of many code examples throughout the Astra DB Serverless documentation.

Astra DB Serverless databases organize data into collections within keyspaces. When you connect to a database, you can specify a target keyspace, also referred to as the working keyspace. If not provided, the default is default_keyspace.

For information about using the Data API clients and Astra CLI for database administration, such as creating databases and keyspaces, see the Databases reference.

  • Python

  • TypeScript

  • Java

  • curl

For more information, see the Client reference.

Get a reference to an existing database with the working keyspace set to the default keyspace or a specific keyspace:

# Connect to a database by database endpoint
# Default keyspace, long form
database = client.get_database("API_ENDPOINT")
# Default keyspace, short form
database = client["API_ENDPOINT"]
# Explicit keyspace
database = client.get_database("API_ENDPOINT", keyspace="KEYSPACE_NAME")

Parameters:

Name Type Summary

api_endpoint

str

A database API endpoint URL, such as \https://DATABASE_ID-REGION.apps.astra.datastax.com.

token

Optional[str]

If supplied, is passed to the Database instead of the client token.

keyspace

Optional[str]

By default, the working keyspace is default_keyspace. Include keyspace to specify a different working keyspace.

Returns:

Database - An instance of the Database class.

Example response (shortened for clarity)
Database(api_endpoint="https://012...datastax.com", token="AstraCS:aAbB...", keyspace="default_keyspace")
  • An instance of the Database class always has a notion of working keyspace. You can pass a keyspace explicitly or use the system default of default_keyspace.

    Some subsequent operations with the database act on the working keyspace, unless you pass a different keyspace in the method invocation. Such operations include get_collection, create_collection, list_collection_names, list_collections, and command.

    You can use the use_keyspace method to change the Database instance’s working keyspace, for example: my_database.use_keyspace("my_other_keyspace"). This doesn’t change the parent keyspace for any collections previously created from that Database instance.

  • Most astrapy objects have an asynchronous counterpart that you can use within the asyncio framework. To get an AsyncDatabase, clients expose a get_async_database method. Likewise, synchronous Databases have a to_async method as well.

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")

# Connect to database
database = client.get_database("API_ENDPOINT")

# Run an operation on the database
collection = database.create_collection("movies", dimension=5)
collection.insert_one({
    "title": "The Title",
    "$vector": [0.1, 0.3, -0.7, 0.9, -0.1],
})

For more information, see the Client reference.

Get a reference to an existing database with the working keyspace set to the default keyspace or a specific keyspace:

// Connect to a database by database endpoint
// Default keyspace
const db = client.db('API_ENDPOINT');
// Explicit keyspace
const db = client.db('API_ENDPOINT', { keyspace: 'KEYSPACE_NAME' });

Parameters:

Name Type Summary

endpoint

string

A database API endpoint URL, such as \https://DATABASE_ID-REGION.apps.astra.datastax.com.

options?

DbSpawnOptions

The options to use for the database. You can override keyspace in method calls.

Options (DbSpawnOptions):

If you set any of these options through the client, then those values act as the actual defaults for these options. For example, if you set keyspace in the client, that value is automatically used as the default keyspace instead of 'default_keyspace'.

Name Type Summary

keyspace?

string

The keyspace to use for the database. The defaults is 'default_keyspace'. You can override this in method calls.

monitorCommands?

boolean

Whether to monitor commands through CommandEvents, using the client as an event emitter. Defaults to false.

token?

string

Access token to use for the database. The default is the client’s token. Typically starts with AstraCS:.

dataApiPath?

string

Path to the Data API. The default is 'api/json/v1'.

Returns:

Db - An unverified reference to the database.

Example response
Db { keyspace: 'default_keyspace' }

An instance of the Db class always has a notion of working keyspace. You can pass a keyspace explicitly or use the system default of 'default_keyspace'.

Some subsequent operations with the database act on the working keyspace, unless you pass a different keyspace in the method invocation. Such operations include collection, createCollection, dropCollection, listCollections, and command.

You can use the useKeyspace method to change the Db instance’s working keyspace, for example: db.useKeyspace('my_other_keyspace'). This doesn’t change the parent keyspace for any collections previously created from that Db instance.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

const client = new DataAPIClient('TOKEN');

// Connect to database by database endpoint and
// override default options for keyspace and token.
const db2 = client.db('API_ENDPOINT', {
  keyspace: 'KEYSPACE_NAME',
  token: 'WEAKER_TOKEN',
});

// Run an operation on the database
(async function () {
  const collection = db1.collection('movies');
  await collection.insertOne({ title: 'The Italian Job', $vector: [...] });
})();

For more information, see the Client reference.

Get a reference to an existing database with the working keyspace set to the default keyspace or a specific keyspace:

// Connect to a database by database endpoint
// Default keyspace
Database db = client.getDatabase(String apiEndpoint);
// Explicit keyspace
Database db = client.getDatabase(String apiEndpoint, String keyspace);

// Connect to a database by database ID and optional region
// Default keyspace
Database db = client.getDatabase(UUID databaseId, String region);
// Explicit keyspace
Database db = client.getDatabase(UUID databaseId, String keyspace, String region);

Parameters:

Name Type Summary

apiEndpoint or databaseId

String or UUID

Either a database API endpoint URL, such as \https://DATABASE_ID-REGION.apps.astra.datastax.com, or a database ID. DataStax recommends using the database API endpoint.

If you use the database ID, you can optionally specify a region for multi-region databases. The endpoint URL is constructed from the database ID and the default or specified region.

keyspace

String

The working keyspace to use. If not provided, the default is default_keyspace.

region

String

The region to use for connecting to the database. The database must be deployed in that region. You can’t set the region parameter when you use an API endpoint instead of an ID. If you don’t set this parameter and the region can’t be inferred from an API endpoint, an additional DevOps API request is made to determine the default region and use it in subsequent operations.

Returns:

Database - An instance of the Database class.

Example response
com.datastax.astra.client.Database@378bf509

An instance of the Database class always has a notion of working keyspace. You can pass a keyspace explicitly or use the system default of default_keyspace.

Some subsequent operations with the database act on the working keyspace, unless you pass a different keyspace in the method invocation. Such operations include getCollection, createCollection, listCollectionNames, listCollections, and runCommand.

You can use the useKeyspace method to change the Database instance’s working keyspace, for example: db.useKeyspace("my_other_keyspace");. This doesn’t change the parent keyspace for any collections previously created from that Database instance.

Example:

package com.datastax.astra.client;

import java.util.UUID;

public class Connecting {
    public static void main(String[] args) {
        // Preferred Access with DataAPIClient (default options)
        DataAPIClient client = new DataAPIClient("TOKEN");

        // Overriding the default options
        DataAPIClient client1 = new DataAPIClient("TOKEN", DataAPIOptions
                .builder()
                .withMaxTimeMS(10)
                .withHttpConnectTimeout(10)
                .build());

        // Access the Database from its endpoint
        Database db1 = client1.getDatabase("API_ENDPOINT");
        Database db2 = client1.getDatabase("API_ENDPOINT", "KEYSPACE");

        // Access the Database from its endpoint
        UUID databaseId = UUID.fromString("f5abf92f-ff66-48a0-bbc2-d240bc25dc1f");
        Database db3 = client.getDatabase(databaseId);
        Database db4 = client.getDatabase(databaseId, "KEYSPACE");
        Database db5 = client.getDatabase(databaseId, "KEYSPACE", "us-east-2");

        db5.useNamespace("yet_another");

    }
}

You inherently connect to a database when you send requests to the Data API. The first part of the endpoint URL specifies the target database, and then you specify the working keyspace as a path parameter.

The specified application token must have sufficient permissions to perform the requested operations on the specified database.

curl -sS --location -X POST "ASTRA_DB_ENDPOINT/api/json/v1/KEYSPACE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{}'

The preceding example returns an error because the request doesn’t include a command to execute:

{
  "errors": [
    {
      "message":"Request invalid: field 'command' value `null` not valid. Problem: must not be null.",
      "errorCode":"COMMAND_FIELD_INVALID"
    }
  ]
}

Parameters:

Name Type Summary

APPLICATION_TOKEN

string

The database’s application token.

ASTRA_DB_ENDPOINT

string

The database’s API endpoint URL.

KEYSPACE_NAME

string

The working keyspace to use. All Serverless (Vector) databases have an initial default keyspace called default_keyspace.

Next steps

After you connect to a database, you can work with the collections and documents in it. You can also programmatically manage databases and keyspaces.

For more information about Astra DB APIs, see Intro to Astra DB APIs.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 DataStax | Privacy policy | Terms of use

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com