Start with the Data API

You can interact with the Data API directly or through the clients. Clients are available for Python, TypeScript, and Java.

Prerequisites

Review the prerequisites and other information about the available 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:

HCD APIs use the term keyspace to refer to both namespaces and keyspaces.

Connect to the database

When you create apps using the Data API clients for Python, TypeScript, and Java, your main entry point is the DataAPIClient object. Using an authentication token, the client can produce a reference to a database. For self-managed databases, you can specify the authentication token using the UsernamePasswordTokenProvider class.

  • Python

  • TypeScript

  • Java

View this topic in more detail on the API Reference.

token_provider = UsernamePasswordTokenProvider(DB_USERNAME, DB_PASSWORD)

# Initialize the client and get a "Database" object
database = DataAPIClient(
    token=token_provider, environment=Environment.HCD,
).get_database(DB_API_ENDPOINT)

Returns:

database - An instance of the Database class.

Example response
Database(api_endpoint="http://localhost:8181", token="Cassandra:dX...", keyspace="(not set)")
Name Type Summary

username

str

A username for token creation. Example: cassandra.

password

str

A password for token creation. Example: cassandra.

Parameters for DataAPIClient:

Name Type Summary

token

Optional[Union[TokenProvider, str]]

The authentication token. It can be a string or an instance of an astrapy.authentication.TokenProvider.

environment

str

The target Data API environment. Accepted values are grouped into astrapy.constants.Environment—for example, Environment.HCD. You can also pass strings directly—for example,"hcd".

Parameters for get_database:

Name Type Summary

api_endpoint

str

The URL for the API endpoint base URL, such as "http://localhost:8181".

token

Optional[Union[TokenProvider, str]]

A specialized token, which overrides — if provided — the one previously given to the client.

keyspace

Optional[str]

Pass this argument to set a working keyspace for the returned Database. If this argument isn’t provided, the database object won’t be able to perform some operations yet. See Create a keyspace for a suggested pattern when the keyspace is yet to be created (such as on a fresh HCD instance).

Example:

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Database settings
DB_USERNAME = "cassandra"
DB_PASSWORD = "cassandra"
DB_API_ENDPOINT = "http://localhost:8181"

# Prepare a token provider
token_provider = UsernamePasswordTokenProvider(DB_USERNAME, DB_PASSWORD)

# Initialize the client and get a "Database" object
client = DataAPIClient(token=token_provider, environment=Environment.HCD)
database = client.get_database(DB_API_ENDPOINT)

Most astrapy objects have an asynchronous counterpart to use within the asyncio framework. To get an AsyncDatabase, use the get_async_database method of the client, or call the database.to_async() method on the synchronous database.

async_db = client.get_database(
    DB_API_ENDPOINT,
    keyspace="the_keyspace",
)
col_names = await async_db.list_collection_names()

my_collection = await async_db.get_collection("the_collection")
await my_collection.insert_one({"_id": 10})

See the API reference for AsyncDatabase to start exploring the async API.

View this topic in more detail on the API Reference.

// Build a token in the required format
const tp = new UsernamePasswordTokenProvider(DB_USERNAME, DB_PASSWORD);

// Initialize the client and get a "Db" object
const client = new DataAPIClient({ environment: 'hcd' });

Returns:

DataAPIClient - An instance of the client class.

Example response
DB_USERNAME = "cassandra"
DB_PASSWORD = "cassandra"
DB_ENVIRONMENT = "hcd"

# Build a token
tp = UsernamePasswordTokenProvider(DB_USERNAME, DB_PASSWORD)

# Initialize the client and get a "Database" object
client = DataAPIClient(token=tp, environment=Environment.DB_ENVIRONMENT)

Parameters:

Name Type Summary

username

str

A username for token creation. Example: cassandra.

password

str

A password for token creation. Example: cassandra.

options?

DataAPIClientOptions

The options to use for the client, including defaults.

Name Type Summary

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, UsernamePasswordTokenProvider, VectorDoc, UUID } from '@datastax/astra-db-ts';

// Database settings
const DB_USERNAME = "cassandra";
const DB_PASSWORD = "cassandra";
const DB_API_ENDPOINT = "http://localhost:8181";
const DB_ENVIRONMENT = "hcd";
const DB_KEYSPACE = "cycling";

// Database settings if you exported them as environment variables
// const DB_USERNAME = process.env.DB_USERNAME;
// const DB_PASSWORD = process.env.DB_PASSWORD;
// const DB_API_ENDPOINT = process.env.DB_API_ENDPOINT;

// OpenAI settings
const OPEN_AI_PROVIDER = "openai";
const OPENAI_API_KEY = process.env.OPENAI_API_KEY
const MODEL_NAME = "text-embedding-3-small";

// Build a token in the required format
const tp = new UsernamePasswordTokenProvider(DB_USERNAME, DB_PASSWORD);

// Initialize the client and get a "Db" object
const client = new DataAPIClient({ environment: 'hcd' });
const db = client.db(DB_API_ENDPOINT, { token: tp });
const dbAdmin = db.admin({ environment: 'hcd' });
// Build a token in the form of Cassandra:base64(username):base64(password)
String token = new UsernamePasswordTokenProvider(cassandraUserName, cassandraPassword).getTokenAsString();
System.out.println("1/7 - Creating Token: " + token);

// Initialize the client
DataAPIClient client = new DataAPIClient(token, builder().withDestination(databaseEnvironment).build());

Returns:

DataAPIClient - An instance of the client class.

Parameters:

Name Type Summary

username

str

A username for token creation. Example: cassandra.

password

str

A password for token creation. Example: cassandra.

options

DataAPIOptions

A class wrapping the advanced configuration of the client such as as HttpClient settings (timeouts…​).

Example:

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.Database;
import com.datastax.astra.client.admin.DataAPIDatabaseAdmin;
import com.datastax.astra.client.model.CollectionOptions;
import com.datastax.astra.client.model.CommandOptions;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.FindOneOptions;
import com.datastax.astra.client.model.KeyspaceOptions;
import com.datastax.astra.client.model.SimilarityMetric;
import com.datastax.astra.internal.auth.UsernamePasswordTokenProvider;

import java.util.Optional;

import static com.datastax.astra.client.DataAPIClients.DEFAULT_ENDPOINT_LOCAL;
import static com.datastax.astra.client.DataAPIOptions.DataAPIDestination.HCD;
import static com.datastax.astra.client.DataAPIOptions.builder;
import static com.datastax.astra.client.model.Filters.eq;

public class QuickStartHCD {

    public static void main(String[] args) {

        // Database Settings
        String cassandraUserName     = "cassandra";
        String cassandraPassword     = "cassandra";
        String dataApiUrl            = DEFAULT_ENDPOINT_LOCAL;  // http://localhost:8181
        String databaseEnvironment   = "HCD" // DSE, HCD, or ASTRA
        String keyspaceName          = "ks1";
        String collectionName        = "lyrics";

        // Database settings if you export them as environment variables
        // String cassandraUserName            = System.getenv("DB_USERNAME");
        // String cassandraPassword            = System.getenv("DB_PASSWORD");
        // String dataApiUrl                   = System.getenv("DB_API_ENDPOINT");
        // OpenAI Embeddings
        String openAiProvider        = "openai";
        String openAiKey             = System.getenv("OPENAI_API_KEY"); // Need to export OPENAI_API_KEY
        String openAiModel           = "text-embedding-3-small";
        int openAiEmbeddingDimension = 1536;

        // Build a token in the form of Cassandra:base64(username):base64(password)
        String token = new UsernamePasswordTokenProvider(cassandraUserName, cassandraPassword).getTokenAsString();
        System.out.println("1/7 - Creating Token: " + token);

        // Initialize the client
        DataAPIClient client = new DataAPIClient(token, builder().withDestination(databaseEnvironment).build());
        System.out.println("2/7 - Connected to Data API");

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