Instantiate a client object

All Data API interactions through a client start with a DataAPIClient object. Once you have a DataAPIClient object, you can connect to a database and the perform CRUD operations on your data.

Creating a client object is an essential component of Data API client scripts. For more information, see Get started with the Data API.

For more information about the Data API client hierarchy, see Python client usage, TypeScript client usage, and Java client usage.

Result

  • Python

  • TypeScript

  • Java

Returns a DataAPIClient object that you can use to interact with the Data API.

Returns a DataAPIClient object that you can use to interact with the Data API.

Returns a DataAPIClient object that you can use to interact with the Data API.

Parameters

  • Python

  • TypeScript

  • Java

Name Type Summary

token

str | TokenProvider

Optional. An application token for a database, in the form of an "AstraCS:…​" string, or an instance of TokenProvider.

The token should have sufficient permissions to perform the desired operations.

DataAPIClient objects aren’t specific to a database. Therefore, when you instantiate a client, you can omit this parameter and specify a token later with client.get_database() or client.get_admin().

environment

str

Optional. Specify the environment this client will work in.

Must be one of the values in astrapy.constants.Environment (or an equivalent string).

Default: Environment.PROD.

callers

list[tuple[str, str]]

Optional. Attaches special identifying entries to the User-Agent header for all HTTP requests issued to the Data API.

The full type of this parameter is Sequence[tuple[str | None, str | None]]. Each 2-item tuple in the sequence is a (caller_name, caller_version) pair: to form the final header, they will be joined and attached to the default, which is something like "astrapy/2.0.1".

api_options

APIOptions

Optional. A complete or partial specification of the APIOptions for the client. This allows you to customize the client interaction with the Data API. For example, you can use this parameter to change the timeout settings.

Name Type Summary

token

string

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

The token should have sufficient permissions to perform the desired operations.

DataAPIClient objects aren’t specific to a database. Therefore, when you instantiate a client, you can omit this parameter and specify a token later with client.db() or client.admin().

options

DataAPIClientOptions

Optional. The options to use for the client, including defaults. See the options table for more details.

Properties of options
Name Type Summary

environment

DataAPIEnvironment

Optional. Specify the environment this client will work in.

Can be one of: astra, dse, hcd, cassandra, other

For more information, see the astra-db-ts README.

Default: astra

httpOptions

DataAPIClientOptions

Optional. Options related to the API requests made by the client.

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

dbOptions

RootDbOptions

Optional. Specify default options for when spawning a Db instance.

adminOptions

RootAdminOptions

Optional. Specify default options for when spawning an Admin instance.

Name Type Summary

token

String

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

The token should have sufficient permissions to perform the desired operations.

DataAPIClient objects aren’t specific to a database. Therefore, when you instantiate a client, you can omit this parameter and specify a token later with client.getDatabase() or client.getAdmin().

options

DataAPIClientOptions

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

Examples

The following examples demonstrate how to instantiate a client.

Instantiate a client

  • Python

  • TypeScript

  • Java

from astrapy import DataAPIClient

client = DataAPIClient()
import { DataAPIClient } from '@datastax/astra-db-ts';

const client = new DataAPIClient();
package com.examples;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.core.options.DataAPIClientOptions;

public class InstantiateClient {

    public static void main(String[] args) {
        DataAPIClient client = new DataAPIClient(new DataAPIClientOptions());
    }
}

Instantiate a client and pass a token

  • Python

  • TypeScript

  • Java

from astrapy import DataAPIClient

client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
import { DataAPIClient } from '@datastax/astra-db-ts';

const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
package com.examples;

import com.datastax.astra.client.DataAPIClient;

public class InstantiateClient {

    public static void main(String[] args) {
        DataAPIClient client = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN");
    }
}

Instantiate a client and specify options

  • Python

  • TypeScript

  • Java

from astrapy import DataAPIClient
from astrapy.api_options import (
    APIOptions,
    SerdesOptions,
    TimeoutOptions,
)
from astrapy.authentication import (
    AWSEmbeddingHeadersProvider,
)

client = DataAPIClient(
    api_options=APIOptions(
        embedding_api_key=AWSEmbeddingHeadersProvider(
            embedding_access_id="my-access-id",
            embedding_secret_id="my-secret-id",
        ),
        timeout_options=TimeoutOptions(
            request_timeout_ms=15000,
            general_method_timeout_ms=30000,
            table_admin_timeout_ms=120000,
        ),
        serdes_options=SerdesOptions(
            custom_datatypes_in_reading=False,
            use_decimals_in_collections=True,
        ),
    )
)
import { DataAPIClient } from '@datastax/astra-db-ts';
import * as fetchH2 from "fetch-h2";

const client = new DataAPIClient({
  logging: [
    { events: "commandStarted", emits: "stdout" },
    { events: "commandFailed", emits: "stderr" },
  ],
  httpOptions: { client: "fetch-h2", fetchH2: fetchH2 },
  timeoutDefaults: {
    requestTimeoutMs: 20000,
    generalMethodTimeoutMs: 40000,
  },
});
package com.examples;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIDestination;
import com.datastax.astra.client.core.headers.AWSEmbeddingHeadersProvider;
import com.datastax.astra.client.core.headers.EmbeddingAPIKeyHeaderProvider;
import com.datastax.astra.client.core.http.HttpClientOptions;
import com.datastax.astra.client.core.http.HttpProxy;
import com.datastax.astra.client.core.options.DataAPIClientOptions;
import com.datastax.astra.client.core.options.TimeoutOptions;
import com.datastax.astra.internal.command.CommandObserver;
import com.datastax.astra.internal.command.ExecutionInfos;

import java.net.http.HttpClient;
import java.time.Duration;

public class InstantiateClient {

    public static void main(String[] args) {
        DataAPIClientOptions options = new DataAPIClientOptions();

        // Specify the environment
        options.destination(DataAPIDestination.ASTRA);

        // Specify the HTTP client
        HttpClientOptions httpClientOptions = new HttpClientOptions()
            .retryCount(3).retryDelay(Duration.ofMillis(200))
            .httpRedirect(HttpClient.Redirect.NORMAL)
            .httpVersion(HttpClient.Version.HTTP_2)
            .httpProxy(new HttpProxy().hostname("localhost").port(8080));
        options.httpClientOptions(httpClientOptions);

        // Specify timeouts
        TimeoutOptions timeoutsOptions = new TimeoutOptions()
            .collectionAdminTimeoutMillis(5000)
            .collectionAdminTimeout(Duration.ofMillis(5000))
            .tableAdminTimeoutMillis(5000)
            .tableAdminTimeout(Duration.ofMillis(5000))
            .databaseAdminTimeoutMillis(15000)
            .databaseAdminTimeout(Duration.ofMillis(15000))
            .generalMethodTimeoutMillis(1000)
            .generalMethodTimeout(Duration.ofMillis(1000))
            .requestTimeoutMillis(200)
            .requestTimeout(Duration.ofMillis(200))
            .connectTimeoutMillis(100)
            .connectTimeout(Duration.ofMillis(100));
        options.timeoutOptions(timeoutsOptions);

        // Add your application in the chain of callers in the header
        options.addCaller("MySampleApplication", "1.0.0");

        // Add a header to computer embeddings externally
        options.embeddingHeadersProvider(new EmbeddingAPIKeyHeaderProvider("key_embeddings"));
        options.embeddingHeadersProvider(new AWSEmbeddingHeadersProvider("aws_access_key", "aws_secret_key"));

        // Add headers to calls for admin or database operations
        options.addAdminAdditionalHeader("X-My-Header", "MyValue");
        options.addDatabaseAdditionalHeader("X-My-Header", "MyValue");

        // Add loggers and observers
        options.addObserver("my_dummy_logger", new CommandObserver() {
            @Override
            public void onCommand(ExecutionInfos executionInfo) {
                System.out.println("Command executed: " + executionInfo.getCommand().getName());
            }
        });
        // Get a sl4j logger at debug level
        options.logRequests();

        DataAPIClient client = new DataAPIClient(options);
    }
}

Client reference

  • Python

  • TypeScript

  • Java

For more information, see the client reference.

For more information, see the client reference.

For more information, see the client reference.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | Privacy policy | Terms of use | Manage Privacy Choices

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