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:

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. The client only needs a token, as it is not specific to a database. For self-managed databases, the token is created using UsernamePasswordTokenProvider.

  • Python

  • TypeScript

  • Java

View this topic in more detail on the API Reference.

# 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)

Returns:

DataAPIClient - An instance of the client class.

Example response
DB_USERNAME = "cassandra"
DB_PASSWORD = "cassandra"

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

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

Parameters:

Name Type Summary

username

str

A username for token creation. Example: cassandra.

password

str

A password for token creation. Example: cassandra.

environment

str

The environment to use with Environment. Example: DSE.

Example:

import os

from astrapy import DataAPIClient
from astrapy.constants import Environment
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import VectorMetric
from astrapy.ids import UUID
from astrapy.exceptions import InsertManyException
from astrapy.info import CollectionVectorServiceOptions

# Database settings
DB_USERNAME = "cassandra"
DB_PASSWORD = "cassandra"
DB_API_ENDPOINT = "http://localhost:8181"
DB_NAMESPACE = "my_namespace"
DB_COLLECTION = "vector_test"

# Database settings if you exported them as environment variables
# DB_USERNAME = os.environ.get("DB_USERNAME")
# DB_PASSWORD = os.environ.get("DB_PASSWORD")
# DB_API_ENDPOINT = os.environ.get("DB_API_ENDPOINT")

# Embedding provider settings
EMBEDDING_PROVIDER = "openai";
EMBEDDING_MODEL_NAME = "text-embedding-3-small";
EMBEDDING_DIMENSIONS = 1024
EMBEDDING_API_KEY = os.environ.get("EMBEDDING_API_KEY");

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

# Initialize the client and get a "Database" object
client = DataAPIClient(environment=Environment.DSE)
database = client.get_database(DB_API_ENDPOINT, token=tp)
database.get_database_admin().create_namespace(DB_NAMESPACE, update_db_namespace=True)

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: DB_ENVIRONMENT });

Returns:

DataAPIClient - An instance of the client class.

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

# 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 = "dse";
const DB_NAMESPACE = "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: DB_ENVIRONMENT });
const db = client.db(DB_API_ENDPOINT, { token: tp });
const dbAdmin = db.admin({ environment: DB_ENVIRONMENT });
// 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.NamespaceOptions;
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 QuickStartDSE69 {

    public static void main(String[] args) {

        // Database Settings
        String cassandraUserName     = "cassandra";
        String cassandraPassword     = "cassandra";
        String dataApiUrl            = DEFAULT_ENDPOINT_LOCAL;  // http://localhost:8181
        String databaseEnvironment   = "DSE" // 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