Get started with the Data API
You can interact with the Data API through clients or directly through HTTP.
Prerequisites
-
An active Astra account
-
An active Serverless (Vector) database
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:
-
Verify that pip is version 23.0 or later:
pip --version
-
If needed, upgrade pip:
python -m pip install --upgrade pip
-
Install the astrapy package . You must have Python 3.8 or later.
pip install astrapy
Install the TypeScript client:
-
Verify that Node is version 18 or later:
node --version
-
Install astra-db-ts 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
-
Install Java 11 or later and Maven 3.9 or later.
-
Create a
pom.xml
file in the root of your project, and then replaceVERSION
with the latest version of astra-db-java .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>
-
Install Gradle and Java 11 or later.
-
Create a
build.gradle
file in the root of your project:build.gradleplugins { 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:
-
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. -
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 |
---|---|---|
|
|
An application token for a database, in the form of |
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 |
---|---|---|
|
|
An application token for a database.
Tokens are prefixed with You can omit this and, instead, pass it with |
|
The options to use for the client, including defaults. |
Options (DataAPIClientOptions
):
Name | Type | Summary |
---|---|---|
Sets the Data API backend to use (for example, Most operations are the same between backends. Authentication and available administration operations can differ. For more information, see the astra-db-ts README. |
||
Options related to the API requests the client makes. |
||
Allows default options for when spawning a Db instance. |
||
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: Usefetch-h2
if available or fall back tofetch
. -
client: 'default'
or unset: Usefetch-h2
if available or throw an error. -
client: 'fetch'
: Only use the nativefetch
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 |
---|---|---|
|
|
An application token for a database.
Tokens are prefixed with |
|
A class wrapping the advanced configuration of the client, such as as |
Returns:
DataAPIClient
- An instance of the client class.
Example:
package com.datastax.astra.client;
import com.datastax.astra.client.databases.Database;
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
.
Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces. |
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 | ||
---|---|---|---|---|
|
|
A database API endpoint URL, such as |
||
|
|
If supplied, is passed to the Database instead of the client token. |
||
|
|
By default, the working keyspace is
|
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")
|
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 |
---|---|---|
|
|
A database API endpoint URL, such as |
|
The options to use for the database.
You can override |
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 | ||
---|---|---|---|---|
|
The keyspace to use for the database.
The defaults is
|
|||
|
Whether to monitor commands through |
|||
|
Access token to use for the database.
The default is the client’s token.
Typically starts with |
|||
|
Path to the Data API.
The default is |
Returns:
Db
- An unverified reference to the database.
Example response
Db { keyspace: 'default_keyspace' }
An instance of the Some subsequent operations with the database act on the working keyspace,
unless you pass a different keyspace in the method invocation.
Such operations include
You can use the |
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 | ||
---|---|---|---|---|
|
|
Either a database API endpoint URL, such as 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. |
||
|
|
The working keyspace to use.
If not provided, the default is
|
||
|
|
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 Some subsequent operations with the database act on the working keyspace,
unless you pass a different keyspace in the method invocation.
Such operations include You can use the |
Example:
package com.datastax.astra.client;
import com.datastax.astra.client.databases.Database;
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 | ||
---|---|---|---|---|
|
|
The database’s application token. |
||
|
|
The database’s API endpoint URL. |
||
|
|
The working keyspace to use.
All Serverless (Vector) databases have an initial default keyspace called
|
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.