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 internals, TypeScript client internals, Go client internals, Java client internals, and C# client internals.

Result

  • Python

  • TypeScript

  • Go

  • Java

  • C#

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.

The Go client is in preview. For more information, see astra-db-go.

Returns a DataAPIClient struct 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

  • Go

  • Java

  • C#

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 Properties of options 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.

The Go client is in preview. For more information, see astra-db-go.

Use the NewClient method.

Method signature
func NewClient(
  opts ...options.APIOption
) *DataAPIClient
Name Type Summary

opts

…​options.APIOption

Optional. A specification of options to override the inherited defaults. Use this to customize the interaction of the client with the admin object. For example, you can change the default timeouts or token.

You can override these options later with client.Database(), client.Admin(), or any downstream Data API operations.

See Methods of the options.APIOption builder for more details.

Methods of the options.APIOption builder
Method Summary

SetToken(token string)

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

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

SetAstraEnvironment(v AstraEnvironment)

Optional. Specify the environment this client will work in.

Default: options.AstraEnvironmentProd.

SetDataAPIBackend(v options.DataAPIBackend)

Optional. Sets the database backend.

Default: options.DataAPIBackendAstra

SetKeyspace(v string)

Optional The keyspace to use for downstream operations.

Default: default_keyspace

AddHeader(key string, value string)

Optional. Specifies headers for all HTTP requests to the Data API.

AddCaller(name string, version string)

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

SetAPIVersion(v string)

Sets the Data API version.

Default: v1

SetHTTPClient(v *http.Client)

Optional. Sets the HTTP client to use for requests.

SetWarningHandler(handler options.WarningHandler)

Optional. Specifies a callback function that is invoked for warnings emitted by the Data API. Data API warnings indicate non-fatal conditions that don’t prevent the operation from completing, such as missing indexes or deprecated features.

UpdateSerdes(v …​options.SerdesOption)

Optional. Sets the serialization/deserialization options.

Name Type Summary

token

String

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

Name Type Summary

token

string

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

CommandOptions

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

Examples

The following examples demonstrate how to instantiate a client.

Instantiate a client

  • Python

  • TypeScript

  • Go

  • Java

  • C#

from astrapy import DataAPIClient

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

const client = new DataAPIClient();

The Go client is in preview. For more information, see astra-db-go.

package main

import (
	"github.com/datastax/astra-db-go/v2/astra"
)

func main() {
	_ = astra.NewClient()
}
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.core.options.DataAPIClientOptions;

public class Example {

  public static void main(String[] args) {
    DataAPIClient client = new DataAPIClient(new DataAPIClientOptions());
  }
}
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static void Main()
  {
    var client = new DataAPIClient();
  }
}

Instantiate a client and pass a token

  • Python

  • TypeScript

  • Go

  • Java

  • C#

from astrapy import DataAPIClient

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

const client = new DataAPIClient("APPLICATION_TOKEN");

The Go client is in preview. For more information, see astra-db-go.

package main

import (
	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	_ = astra.NewClient(options.API().SetToken("APPLICATION_TOKEN"))
}
import com.datastax.astra.client.DataAPIClient;

public class Example {
  public static void main(String[] args) {
    DataAPIClient client = new DataAPIClient("APPLICATION_TOKEN");
  }
}
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static void Main()
  {
    var client = new DataAPIClient("APPLICATION_TOKEN");
  }
}

Instantiate a client and specify options

  • Python

  • TypeScript

  • Go

  • Java

  • C#

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,
  },
});

The Go client is in preview. For more information, see astra-db-go.

package main

import (
	"time"

	"github.com/datastax/astra-db-go/v2/astra"
	"github.com/datastax/astra-db-go/v2/astra/options"
)

func main() {
	_ = astra.NewClient(
		options.API().
			SetRequestTimeout(15 * time.Second).
			SetGeneralMethodTimeout(30 * time.Second).
			SetConnectionTimeout(60 * time.Second).
			SetKeyspace("example_keyspace"),
	)
}
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 Example {
  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);
  }
}
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;

namespace Examples;

public class Program
{
  static void Main()
  {
    var options = new CommandOptions()
    {
      TimeoutOptions = new TimeoutOptions()
      {
        ConnectionTimeout = TimeSpan.FromMilliseconds(3000),
        RequestTimeout = TimeSpan.FromMilliseconds(9000),
      },
    };

    var client = new DataAPIClient(options);
  }
}

Client reference

  • Python

  • TypeScript

  • Go

  • Java

  • C#

For more information, see the client reference.

For more information, see the client reference.

The Go client is in preview. For more information, see astra-db-go.

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?

© Copyright IBM Corporation 2026 | 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: Contact IBM