Get a table

This Astra DB Serverless feature is currently in public preview. Development is ongoing, and the features and functionality are subject to change. Astra DB Serverless, and the use of such, is subject to the DataStax Preview Terms.

The Data API tables commands are available through HTTP and the clients.

If you use a client, tables commands are available only in client versions 2.0-preview or later. For more information, see Data API client upgrade guide.

Gets a reference to a table for use with the Data API clients.

Method signature

  • Python

  • TypeScript

  • Java

  • curl

database.get_table(
  name: str,
  *,
  row_type: type[Any],
  keyspace: str,
  embedding_api_key: str | EmbeddingHeadersProvider | UnsetType,
  spawn_api_options: APIOptions | UnsetType,
) -> Table[ROW]
database.table<WSchema extends SomeRow, PKeys extends SomeRow = Partial<FoundRow<WSchema>>, RSchema extends SomeRow = FoundRow<WSchema>>(
  name: string,
  options?: {
    embeddingApiKey?: string | EmbeddingHeadersProvider,
    logging?: DataAPILoggingConfig,
    serdes?: TableSerDesConfig,
    timeoutDefaults?: Partial<TimeoutDescriptor>,
    keyspace?: string,
  },
): Table<WSchema, PKeys, RSchema>
Table<Row> getTable(String tableName)
Table<Row> getTable(
  String tableName,
  TableOptions tableOptions
)
<T> Table<T> getTable(Class<T> rowClass)
<T> Table<T> getTable(
  String tableName,
  Class<T> rowClass
)
<T> Table<T> getTable(
  String tableName,
  Class<T> rowClass,
  TableOptions tableOptions
)

This method has no literal equivalent in HTTP. Instead, you specify the table in the path, if required.

To get information about tables in a database, see List table metadata.

Result

  • Python

  • TypeScript

  • Java

  • curl

Returns a Table object that corresponds to the specified table name.

Unless you specify the row_type parameter, the table is typed as Table[dict].

This method returns a Table object even for tables that don’t exist.

Returns a Table<Schema> object that corresponds to the specified table name.

Unless you specify the Schema, the table is typed as Table<Record<string, any>>.

This method returns a Table object even for tables that don’t exist.

Returns a Table<T> object that corresponds to the specified table name.

Unless you specify the rowClass parameter, the table is typed as Table<Row>.

This method returns a Table object even for tables that don’t exist.

This method has no literal equivalent in HTTP. Instead, you specify the table in the path, if required.

To get information about tables in a database, see List table metadata.

Parameters

  • Python

  • TypeScript

  • Java

  • curl

Name Type Summary

name

str

The name of the table.

row_type

type

This parameter acts a formal specifier for the type checker. If omitted, the resulting Table is implicitly a Table[dict]. If provided, row_type must match the type hint specified in the assignment. For more information, see Typing support.

keyspace

str | None

The keyspace containing the target table. If not specified, the general keyspace setting for the database is used.

embedding_api_key

str | EmbeddingHeadersProvider

Optional parameter for tables that have a vector column with a vectorize embedding provider integration. For more information, see Define a column to automatically generate vector embeddings.

As an alternative to Astra DB KMS authentication, use embedding_api_key to store one or more embedding provider API keys on the Table instance for vectorize header authentication. The client automatically passes the key as an X-embedding-api-key header (EmbeddingAPIKeyHeaderProvider) with operations that use vectorize.

Most embedding provider integrations accept a plain string for header authentication. However, some vectorize providers and models require specialized subclasses of EmbeddingHeadersProvider for header authentication.

spawn_api_options

APIOptions

A complete or partial specification of the APIOptions to override the defaults inherited from the Database. This allows for nuanced table configuration. For example, if APIOptions is passed together with named timeout parameters, the latter take precedence in their respective settings.

Name Type Summary

name

string

The name of the table.

option?

TableOptions

The options for spawning the Table instance.

Options (TableOptions<Schema>):

Name Type Summary

keyspace?

string

The keyspace where the target table exists. If not specified, the working keyspace of the Db is used. For example:

const table = db.table<Schema>('games', {
  keyspace: 'KEYSPACE',
});

embeddingApiKey?

string | EmbeddingHeadersProvider

Optional parameter for tables that have a vector column with a vectorize embedding provider integration. For more information, see Define a column to automatically generate vector embeddings.

As an alternative to Astra DB KMS authentication, use embeddingApiKey to store an embedding provider API key on the Table instance for vectorize header authentication. The client automatically passes the key as an X-embedding-api-key header with operations that use vectorize.

Most embedding provider integrations accept a plain string for header authentication. However, some vectorize providers and models require specialized subclasses of EmbeddingHeadersProvider for header authentication.

logging?

DataAPILoggingConfig

The configuration for logging events emitted by the DataAPIClient.

timeoutDefaults?

Partial<TimeoutDescriptor>

The default timeout options for any operation performed on this Table instance. For more information, see TimeoutDescriptor.

serdes?

TableSerDesConfig

Lower-level serialization/deserialization configuration for this table. For more information, see Custom Ser/Des.

Name Type Summary

name

String

The name of the table.

rowClass

Class<?>

An optional specification of the class of the table’s row object. If not provided, the default is Row, which is close to a Map object.

tableOptions

TableOptions

Specialization of the Table object overriding default configuration (DataAPIOptions).

Options:

Name Type Summary

keyspace

String

The keyspace containing the target table. If not specified, the working keyspace of the Database is used.

timeout

long or Duration

Optional configuration for default timeouts for table operations using this Table object. This is a general method for all operations.

databaseAdditionalHeaders

Map<String, String>

Optional specialized headers for this table, if needed, that are added to the database headers.

embeddingApiKey

String

Optional parameter for tables that have a vector column with a vectorize embedding provider integration. For more information, see Define a column to automatically generate vector embeddings.

As an alternative to Astra DB KMS authentication, use embeddingApiKey to store an embedding provider API key on the Table instance for vectorize header authentication. The client automatically passes the key as an X-embedding-api-key header with operations that use vectorize.

Most embedding provider integrations accept a plain string for header authentication. However, some vectorize providers and models require specialized subclasses of EmbeddingHeadersProvider for header authentication.

EmbeddingHeadersProvider

EmbeddingHeadersProvider

An optional specialization associated with embeddingApiKey.

httpClientOptions

HttpClientOptions

Optional HTTP configuration overrides for this Table instance.

serializer

DataAPISerializer

Optional specialized serializer for this Table instance. If not provided RowSerializer is used.

This method has no literal equivalent in HTTP. Instead, you specify the table in the path, if required.

To get information about tables in a database, see List table metadata.

Examples

The following examples demonstrate how to get a table.

  • Python

  • TypeScript

  • Java

  • curl

Get a Table object from a Database using the working keyspace of the Database:

my_table = database.get_table("games")

By default, get_table uses the database’s working keyspace.

If necessary, you can specify a different keyspace, and you can pass other options for the resulting Table object, such as an embedding_api_key for header-based vectorize authentication:

my_table = database.get_table(
    "games",
    keyspace="the_other_keyspace",
    embedding_api_key="secret-012abc...",
)

Get a typed Table object by supplying a type (a subclass of TypedDict) to its rows:

my_typed_table: Table[MyCustomDictType] = database.get_table(
    "games",
    row_type=MyCustomDictType,
)

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
database = client.get_database("API_ENDPOINT")

from astrapy.constants import SortMode
from astrapy.info import (
    CreateTableDefinition,
    ColumnType,
)

database.create_table(
    "games",
    definition=(
        CreateTableDefinition.builder()
        .add_column("match_id", ColumnType.TEXT)
        .add_column("round", ColumnType.TINYINT)
        .add_vector_column("m_vector", dimension=3)
        .add_column("score", ColumnType.INT)
        .add_column("when", ColumnType.TIMESTAMP)
        .add_column("winner", ColumnType.TEXT)
        .add_set_column("fighters", ColumnType.UUID)
        .add_partition_by(["match_id"])
        .add_partition_sort({"round": SortMode.ASCENDING})
        .build()
    ),
)

# Get a Table object (and read a property of it as an example):
my_table = database.get_table("games")
my_table.full_name
# 'default_keyspace.games'

# Get a Table object in a specific keyspace,
# and set an embedding API key to it:
my_other_table = database.get_table(
    "tournaments",
    keyspace="the_other_keyspace",
    embedding_api_key="secret-012abc...",
)

from astrapy import Table
MyCustomDictType = dict[str, int]

# Get a Table object typed with a specific type for its rows:
my_typed_table: Table[MyCustomDictType] = database.get_table(
    "games",
    row_type=MyCustomDictType,
)

To spawn a Table instance, you must pass a type schema. The TypeScript client offers several ways to type tables, depending on your typing preferences and needs.

  • Schema

  • Schema and primary key

  • Untyped

  • Full generic type signature

The most straightforward way to type a table is to provide a schema object that represents the table’s structure. However, this strategy doesn’t provide any type information about the table’s primary key.

import { DataAPIClient, DataAPITimestamp, DataAPIVector, UUID } from '@datastax/astra-db-ts';

// Instantiate the client and connect to the database
const client = new DataAPIClient();
const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! });

// Define table's type manually
interface TableSchema {
  matchId: string,
  round: number,
  score: number,
  winner: string,
  when: DataAPITimestamp,
  fighters: Set<UUID>,
  mVector: DataAPIVector,
}

// Pass it to db.table to type it as such.
// You must ensure the schema matches the table's actual schema.
const table = db.table<TableSchema>('games');

// You can then use TableSchema as you would any other type.
// @ts-expect-error - 'badfield' is not a valid column as per the table's type
const row: TableSchema = { matchId: 'match01', round: 1, badfield: 'Shhh!' }

// res.insertedId :: Partial<TableSchema>
const res = await table.insertOne(row);

The primary key type is used in the return types of insertOne and insertMany operations only. However, you don’t need to specify the primary key type if you use the default Partial<Schema> as the primary key type or you don’t need to use the returned values from insertOne and insertMany operations.

Partial<Schema> keeps the return type type-safe when the primary key fields are not known. For example, given the following schema:

interface SchemaWithNoPK {
  ptKey: string, // We know this is part of the primary key; TypeScript doesn't
  clKey: string,
  val1?: string | null,
  val2?: number | null,
}
const table = db.table<SchemaWithNoPK>('my_table');

If there is no primary key information provided, then insertOne returns an insertedId like the following:

// `insertedId` is inferred to be `Partial<SchemaWithNoPK>` by default
const inserted = await table.insertOne({ ptKey: 'abc', clKey: 'def', val1: 'val' });
const insertedId = inserted.insertedId;

While not perfect, this option remains relatively type-safe without necessitating that you embed your primary key’s type in the table’s schema’s type itself.

If the primary key type is unspecified, the actual default is Partial<RSchema>, but the difference between Partial<RSchema> and Partial<Schema> is negligible for most use cases. For more information about read and write schemas, see Full generic type signature.

For more precise typing, you can include the primary key information in the table’s type along with the schema. This strategy requires the TS-native Pick utility type to define the primary key type.

import { DataAPIClient, DataAPITimestamp, DataAPIVector, UUID } from '@datastax/astra-db-ts';

// Instantiate the client and connect to the database
const client = new DataAPIClient();
const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! });

// Define table's type manually
interface TableSchema {
  matchId: string,
  round: number,
  score: number,
  winner: string,
  when: DataAPITimestamp,
  fighters: Set<UUID>,
  mVector: DataAPIVector,
}

// Define table's primary key type
type TablePK = Pick<TableSchema, 'matchId' | 'round'>;

// Pass it to db.table to type it as such.
// You must ensure the schema matches the table's actual schema.
const table = db.table<TableSchema, TablePK>('games');

// You can then use TableSchema as you would any other type.
// @ts-expect-error - 'badfield' is not a valid column as per the table's type
const row: TableSchema = { matchId: 'match01', round: 1, badfield: 'Shhh!' }

// res.insertedId :: { matchId: string, round: number }
const res = await table.insertOne(row);

If you want to use a table without any typing, you can pass SomeRow as the single generic type parameter. This types the table’s rows as Record<string, any>, which is the most flexible but least type-safe option.

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

// Instantiate the client and connect to the database
const client = new DataAPIClient();
const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! });

// Pass it to db.table to type it as such.
// You must ensure the schema matches the table's actual schema.
const table = db.table<TableSchema, TablePK>('games');

// You can then use TableSchema as you would any other type.
// @ts-expect-error - 'badfield' is not a valid column as per the table's type
const row: TableSchema = { matchId: 'match01', round: 1, badfield: 'Shhh!' }

// res.insertedId :: { matchId: string, round: number }
const res = await table.insertOne(row);

For the most complex use cases, especially when using custom ser/des logic, consider using the Table full generic type signature:

class Table<
  WSchema extends SomeRow,
  PKey extends SomeRow = Partial<FoundRow<WSchema>>,
  RSchema extends SomeRow = FoundRow<WSchema>,
> {}

For more information, see Collection and Table typing.

Example:

Full script
import { CreateTableDefinition, DataAPIClient, InferTableSchema, SomeRow, timestamp, uuid, vector } from '@datastax/astra-db-ts';

// Instantiate the client and connect to the database
const client = new DataAPIClient();
const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! });

// Create table schema using bespoke Data API table definition syntax
const TableDefinition = <const>{                  // <const> ensures the exact literal type of the object is used, not a widened type
  columns: {
    matchId: 'text',                              // Represented by a native JS string
    round: 'tinyint',                             // All non-varint/decimal numbers are represented as JS numbers
    mVector: { type: 'vector', dimension: 3 },    // Vectors are represented as DataAPIVectors by default to enable some optimizations
    score: 'int',
    when: 'timestamp',                            // Represented by DataAPITimestamps instead of Dates
    winner: 'text',
    fighters: { type: 'set', valueType: 'uuid' }, // Sets/maps/lists are represented as native JS Sets/Maps/Arrays
  },                                              // But the UUID is represented as a provided UUID class.
  primaryKey: {
    partitionBy: ['matchId'],                     // 'matchId' is the sole partition key
    partitionSort: { round: 1 },                  // 'round' is the sole clustering key
  },
} satisfies CreateTableDefinition;                // Ensures the table definition is valid

// Infer the TS-equivalent type from the table definition. Equivalent to:
//
// interface TableSchema {
//   matchId: string,                // Primary key components are not nullable
//   round: number,
//   score?: number | null,          // Non-primary key columns are optional and can return as null
//   winner?: string | null,
//   when?: DataAPITimestamp | null,
//   fighters?: Set<UUID>,           // Maps, lists, and sets are optional to insert, but returns as empty instead of null
//   mVector?: DataAPIVector | null, // Vectors can be null.
// }
//
// The preceding definition uses some custom types, like DataAPITimestamp, UUID, and DataAPIVector.
// If necessary, you can modify the ser/des logic to use different datatypes instead.
// However, you must provide your own types in that case.
// For more information, see the Typescript client usage documentation.
type TableSchema = InferTableSchema<typeof TableDefinition>;

(async function () {
  // Create a table using the given TableSchema type or error if a 'games' table already exists
  const table = await db.createTable<TableSchema>('games', { definition: TableDefinition });

  // Attempt to create the same table again.
  // This errors because a table with the given name already exists,
  // and it uses the default of 'ifNotExists: false'.
  await db.createTable<TableSchema>('games', { definition: TableDefinition })
    .catch((e => console.error(e.message)));

  // Attempt to create the same table again.
  // Because 'ifNotExists: true', the command does not throw an error
  // if the working keyspace already has an table named 'games'.
  await db.createTable<TableSchema>('games', { definition: TableDefinition, ifNotExists: true });

  // Insert a single row
  await table.insertOne({
    matchId: 'match_0',
    round: 1,                                       // All non-varint/decimal numbers are represented as JS numbers
    score: 18,
    when: timestamp(),                              // Shorthand for new DataAPITimestamp(new Date())
    winner: 'Victor',
    fighters: new Set([                             // Uses native Maps/Sets/Arrays for collections
      uuid('a4e4e5b0-1f3b-4b4d-8e1b-4e6b3f1f3b4d'), // You can nest datatypes in collections
      uuid(4),                                      // Shorthand for UUID.v4()
    ]),
    mVector: vector([0.2, -0.3, -0.5]),             // Shorthand for new DataAPIVector([0.2, -0.3, -0.5])
  });

  // Use createTable to create an untyped reference to the table.
  const untypedTable = await db.createTable<SomeRow>('games', { definition: TableDefinition, ifNotExists: true });

  // Attempt to insert a row into the untyped table.
  // This errors at runtime (not statically) because it's untyped.
  await untypedTable.insertOne({ matchId: '32', round: 1, badfield: 3 })
    .catch((e => console.error(e.message)));

  // The following examples demonstrate various ways to get a reference to a table (a Table object)

  // Create the table if it doesn't already exist, but don't retain the Table object
  await db.createTable('games', { definition: TableDefinition, ifNotExists: true });

  // Create an untyped table object
  const untypedTable = db.table('games');

  // Flexible but not type-safe, errors at runtime
  const inserted1 = await untypedTable.insertOne({ matchId: 'fight7' });

  // Return type of inserted primary key not known either
  console.log(inserted1.insertedId["I don't know who I am..."]);

  // Return types of find operations, not type-safe
  const found1 = await untypedTable.findOne({ matchId: 'fight7', round: 3 });
  console.log(found1?.["I guess you could say that I'm having an IDentity crisis :)"]);

  // Create a typed table object
  const typedTable = db.table<TableSchema, TablePK>('games');

  // @ts-expect-error
  // Type-safe, errors when compiling
  // You must ensure the types are correct
  const inserted2 = await typedTable.insertOne({ matchId: 'fight7' });

  // @ts-expect-error
  // Type-safe, errors when compiling
  console.log(inserted2.insertedId["uh oh I've been caught"]);

  // Still type-safe
  const found2 = await typedTable.findOne({ matchId: 'fight7', round: 3 })
  console.log(found2?.winner);

  // Uncomment the following line to drop the table and any related indexes.
  // await table.drop();
})();

Expand the preceding Full script example for the definition of TypeSchema that is used in the following truncated example:

// Create the table if it doesn't already exist, but don't retain the Table object
await db.createTable('games', { definition: TableDefinition, ifNotExists: true });

// Create an untyped table object
const untypedTable = db.table('games');

// Flexible but not type-safe, errors at runtime
const inserted1 = await untypedTable.insertOne({ matchId: 'fight7' });

// Return type of inserted primary key not known either
console.log(inserted1.insertedId["I don't know who I am..."]);

// Return types of find operations, not type-safe
const found1 = await untypedTable.findOne({ matchId: 'fight7', round: 3 });
console.log(found1?.["I guess you could say that I'm having an IDentity crisis :)"]);

// Create a typed table object
const typedTable = db.table<TableSchema, TablePK>('games');

// @ts-expect-error
// Type-safe, errors when compiling
// You must ensure the types are correct
const inserted2 = await typedTable.insertOne({ matchId: 'fight7' });

// @ts-expect-error
// Type-safe, errors when compiling
console.log(inserted2.insertedId["uh oh I've been caught"]);

// Still type-safe
const found2 = await typedTable.findOne({ matchId: 'fight7', round: 3 })
console.log(found2?.winner);

Get a Table object from a Database using the working keyspace of the Database:

Table<Row> myTable = database.getTable("games");

By default, getTable uses the database’s working keyspace.

If necessary, you can specify a different keyspace, and you can pass other options for the resulting Table object, such as an embeddingApiKey for header-based vectorize authentication:

TableOptions options = new TableOptions()
 .keyspace("the_other_keyspace")
 .embeddingApiKey("secret-012abc...");
Table<Row> myTable = db.getTable("games", options);

Get a typed Table object by supplying a type to its rows:

TableOptions options = new TableOptions();
Table<Game> myTable = database
  .getTable("games", Game.class, options);

Example:

package com.datastax.astra.client.database;

import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.auth.EmbeddingAPIKeyHeaderProvider;
import com.datastax.astra.client.core.options.DataAPIClientOptions;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Game;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.TableOptions;
import com.datastax.astra.client.tables.definition.rows.Row;

import java.util.Map;

public class GetTable {

 public static void main(String[] args) {
  // Database astraDb =  new DataAPIClient(token).getDatabase(endpoint);
  Database db =
    DataAPIClients.localDbWithDefaultKeyspace();

  // Default
  Table<Row> myTable1 =
   db.getTable("games");

  // Options
  TableOptions options = new TableOptions()
    .keyspace("the_other_keyspace")
    .embeddingApiKey("secret-012abc...")
    .databaseAdditionalHeaders(Map.of("Feature-Flag-tables", "true"));
  Table<Row> myTable3 = db.getTable("games", options);

  // Typing
  Table<Game> myTable2 =
   db.getTable("games", Game.class);

  // Typing + Options
  Table<Game> myTable4 =
   db.getTable("games", Game.class, new TableOptions());
 }
}

This method has no literal equivalent in HTTP. Instead, you specify the table in the path, if required.

To get information about tables in a database, see List table metadata.

Client reference

  • Python

  • TypeScript

  • Java

  • curl

For more information, see the client reference.

For more information, see the client reference.

For more information, see the client reference.

Client reference documentation is not applicable for HTTP.

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