Start with the Data API

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

Prerequisites

Review the prerequisites and other information about the Astra DB APIs in the API reference overview.

If you plan to use a Data API client, and you haven’t done so already, install the client for your preferred language:

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, for example through cURL, you provide your database’s API endpoint, which specifies the database that you want to interact with. However, when you instantiate a client, you only need a token that has adequate permissions because the client object is not specific to a database.

  • Python

  • TypeScript

  • Java

For more information, see the API reference.

client = DataAPIClient("TOKEN")

Returns:

DataAPIClient - An instance of the client class.

Example response
DataAPIClient("AstraCS:aAbBcC:12345")

Parameters:

Name Type Summary

token

str

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

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],
})
database_by_id = client.get_database("01234567-...")
database_by_id_region = client.get_database("01234567-...", region="us-east1")
admin = client.get_admin()
admin1 = client.get_admin(token=more_powerful_token_override)
database_iterator = admin.list_databases()

For more information, see the API reference.

const client = new DataAPIClient('TOKEN');

Returns:

DataAPIClient - An instance of the client class.

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 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 API reference.

Monitoring/logging:

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

Example:

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

const client = new DataAPIClient('TOKEN');

const db1 = client.db('DB_API_ENDPOINT');
const db2 = client.db('DB_ID', 'REGION');

(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());
})();
// Default Initialization
DataAPIClient client = new DataAPIClient("TOKEN");

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

Returns:

DataAPIClient - An instance of the client class.

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.

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", "NAMESPACE");

        // 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, "NAMESPACE");
        Database db5 = client.getDatabase(databaseId, "NAMESPACE", "us-east-2");

    }
}

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 namespaces. When you connect to a database, you can specify a target namespace, also referred to as the working namespace. 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 namespaces, see the Databases reference.

  • Python

  • TypeScript

  • Java

  • cURL

For more information, see the API reference.

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

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

# Connect to a database by database ID and optional region
# Default namespace, long form
database = client.get_database("ID")
# Default namespace, short form
database = client["ID"]
# Explicit namespace
database = client.get_database("ID", namespace="NAMESPACE", region="REGION")

Parameters:

Name Type Summary

api_endpoint or id

str

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 region for multi-region databases.

token

Optional[str]

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

namespace

Optional[str]

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

region

Optional[str]

The region to use for connecting to the database. The database must be accessible 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 the 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
Database(api_endpoint="https://01234567-89ab-cdef-0123-456789abcdef-us-east1.apps.astra.datastax.com", token="AstraCS:aAbB...", namespace="default_keyspace")
  • An instance of the Database class always has a notion of working namespace. You can pass this explicitly or use the system default of default_keyspace. Some subsequent operations with the database act on the working namespace, unless you pass a different namespace in the method invocation. Such operations include get_collection, create_collection, list_collection_names, list_collections, and command.

  • 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.

    For more information, see the AsyncDatabase API reference.

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 API reference.

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

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

// Connect to a database by database ID and optional region
// Default namespace
const db = client.db('ID', 'REGION');
// Explicit namespace
const db = client.db('ID', 'REGION', { namespace: 'NAMESPACE' });

Parameters:

Name Type Summary

endpoint or id

string

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.

options?

DbSpawnOptions

The options to use for the database. You can override namespace 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 namespace in the client, that value is automatically used as the default namespace instead of 'default_keyspace'.

Name Type Summary

namespace?

string

The namespace 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 { namespace: 'default_keyspace' }

An instance of the Db class always has a notion of working namespace. You can pass this explicitly or use the system default of default_keyspace. Some subsequent operations with the database act on the working namespace, unless you pass a different namespace in the method invocation. Such operations include collection, createCollection, dropCollection, listCollections, and command.

Example:

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

const client = new DataAPIClient('TOKEN');

// Connect to database by database endpoint and
// override default options for namespace and token.
const db2 = client.db('API_ENDPOINT', {
  namespace: 'NAMESPACE',
  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 API reference.

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

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

// Connect to a database by database ID and optional region
// Default namespace
Database db = client.getDatabase(UUID databaseId, String region);
// Explicit namespace
Database db = client.getDatabase(UUID databaseId, String namespace, 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.

namespace

String

The working namespace 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 namespace. You can pass this explicitly or use the system default of default_keyspace. Some subsequent operations with the database act on the working namespace, unless you pass a different namespace in the method invocation. Such operations include getCollection, createCollection, listCollectionNames, listCollections, and runCommand.

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", "NAMESPACE");

        // 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, "NAMESPACE");
        Database db5 = client.getDatabase(databaseId, "NAMESPACE", "us-east-2");

    }
}

You connect to a database inherently when you send requests to the Data API. The target database is supplied in the endpoint URL and the application token. You specify the working namespace as a path parameter.

curl -s --location \
--request POST ${API_ENDPOINT}/api/json/v1/${NAMESPACE} \
--header "Token: ${APPLICATION_TOKEN}" \
--header "Content-Type: application/json" \
--data '{}'
Example response

The 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.

ASTRA_DB_KEYSPACE

string

The working namespace to use. All Astra DB Serverless databases have an initial default namespace called default_keyspace.

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