Developing with the Astra DB REST API

The REST API exposes CRUD access to data stored in Cassandra tables.

Prerequisites

If you haven’t already, create a database using Astra DB.

  • Install cURL, a utility for running REST, Document, or GraphQL queries on the command line.

  • [Optional] If you prefer, you can use Postman as a client interface for exploring the APIs

    • You will also find links to downloadable collections and environments in Using Postman

  • [Optional] If you going to use the GraphQL API, you will want to use the GraphQL Playground to deploy schema and execute mutations and queries.

  • [Optional] For the REST and Document APIs, you can use the Swagger UI.

Before you get started, set your environment variables to save time developing on your database. There are four environment variables, three of which you will get from the Astra dashboard (database id, region, and keyspace), and one that you must create (token).

  1. In Astra DB, select the database to which you want to connect.

  2. In your Database Dashboard, select Connect.

  3. Select your API.

    If you have multiple regions, select the region you want to connect to from the dropdown menu for instructions.

  4. Follow the steps to get your application token and set up your environment variables. Or if you have an older Astra Classic database, follow the steps in Authentication for classic databases.

API reference

If you prefer to learn using a QuickStart, try out the Stargate REST QuickStart. To view the API Reference, see Astra DB REST API.

Create keyspace

See Adding a new keyspace to add a new keyspace.

Check keyspace existence

To check if a keyspaces exist, execute a REST API query with cURL to find all the keyspaces:

  • cURL command (/v2)

  • Result

curl -s -L -X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json"
{
  "data":[
    {
      "name":"system_distributed"
    },
    {
      "name":"system"
    },
    {
      "name":"data_endpoint_auth"
    },
    {
      "name":"users_keyspace"
    },
    {
      "name":"system_schema"
    },
    {
      "name":"myworld"
    },
    {
      "name":"stargate_system"
    },
    {
      "name":"library"
    },
    {
      "name":"system_auth"
    },
    {
      "name":"system_traces"
    }
  ]
}

To get a particular keyspace, specify the keyspace in the URL:

  • cURL command (/v2)

  • Result

curl -s -L -X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json"
{"data":{"name":"users_keyspace"}}

Create a table in your keyspace

Create tables in your database using the DataStax Astra DB REST API. Use the application token you generated to create a table in your keyspace. A keyspace is like a bucket that holds your tables. You can create different keyspaces for groups of tables.

For example, we’ll use users_keyspace as the keyspace.

  • Optional: A header line using a {unique-UUID}, a randomly-generated UUID that is unique for the authorization request, can be included in the previous command by adding the following line:

 --header 'x-cassandra-request-id: {unique-UUID}'

Create a table

Send a POST request to /api/rest/v2/schemas/keyspaces/{keyspace-name}/tables to create a table. Set the table name and column definitions in the JSON body in the --data field.

  • cURL command (/v2)

  • Result

curl -s --location \
--request POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
	"name": "users",
	"columnDefinitions":
	  [
        {
	      "name": "firstname",
	      "typeDefinition": "text"
	    },
        {
	      "name": "lastname",
	      "typeDefinition": "text"
	    },
        {
	      "name": "favorite color",
	      "typeDefinition": "text"
	    }
	  ],
	"primaryKey":
	  {
	    "partitionKey": ["firstname"],
	    "clusteringKey": ["lastname"]
	  },
	"tableOptions":
	  {
	    "defaultTimeToLive": 0,
	    "clusteringExpression":
	      [{ "column": "lastname", "order": "ASC" }]
	  }
}'
{"name":"users"}

The name of our example table is users. This table column definition includes:

Partition key

One or more columns required. firstname is the partition key.

Clustering key

Optional, but zero, one or more columns can be defined. lastname is the clustering key.

Non-primary key

Optional, but zero, one or more columns that are not a partition key or clustering key can be defined. favorite_color is the non-primary key column.

Notice that each column must have a data type specified.

Optional: Table options can be set. The two options are:

defaultTimeToLive

Sets the default Time-To-Live (TTL).

clusteringExpression

Defines the order, either ascending (ASC) or descending (DESC) for columns that are clustering keys. ASC is the default.

  "tableOptions":
    {
      "defaultTimeToLive": 0,
      "clusteringExpression":
        [{ "column": "lastname", "order": "ASC" }]
    }

Check table and column existence

To check if a table exists, execute a REST API query with cURL to find all the tables:

  • cURL command (/v2)

  • Result

curl -s -L -X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" 
{
  "data": [
    {
      "name": "users",
      "keyspace": "users_keyspace",
      "columnDefinitions": [
        {
          "name": "firstname",
          "typeDefinition": "varchar",
          "static": false
        },
        {
          "name": "lastname",
          "typeDefinition": "varchar",
          "static": false
        },
        {
          "name": "email",
          "typeDefinition": "varchar",
          "static": false
        },
        {
          "name": "favorite color",
          "typeDefinition": "varchar",
          "static": false
        }
      ],
      "primaryKey": {
        "partitionKey": [
          "firstname"
        ],
        "clusteringKey": [
          "lastname"
        ]
      },
      "tableOptions": {
        "defaultTimeToLive": 0,
        "clusteringExpression": [
          {
            "order": "Asc",
            "column": "lastname"
          }
        ]
      }
    }
  ]
}

In this case, we only have one table in the keyspace.

To get a particular table, specify the table in the URL:

  • cURL command (/v2)

  • Result

curl -s -L \
-X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json"
{
  "data": {
    "name": "users",
    "keyspace": "users_keyspace",
    "columnDefinitions": [
      {
        "name": "firstname",
        "typeDefinition": "varchar",
        "static": false
      },
      {
        "name": "lastname",
        "typeDefinition": "varchar",
        "static": false
      },
      {
        "name": "current_country",
        "typeDefinition": "frozen<tuple<varchar, date, date>>",
        "static": false
      },
      {
        "name": "email",
        "typeDefinition": "varchar",
        "static": false
      },
      {
        "name": "evaluations",
        "typeDefinition": "map<int, varchar>",
        "static": false
      },
      {
        "name": "favorite color",
        "typeDefinition": "varchar",
        "static": false
      },
      {
        "name": "favorite_books",
        "typeDefinition": "set<varchar>",
        "static": false
      },
      {
        "name": "top_three_tv_shows",
        "typeDefinition": "list<varchar>",
        "static": false
      }
    ],
    "primaryKey": {
      "partitionKey": [
        "firstname"
      ],
      "clusteringKey": [
        "lastname"
      ]
    },
    "tableOptions": {
      "defaultTimeToLive": 0,
      "clusteringExpression": [
        {
          "order": "ASC",
          "column": "lastname"
        }
      ]
    }
  }
}

Although this command is slightly different, because we have only one table, the command to get all tables and this command to just get the table users return the same information.

Delete a table

Send a DELETE request to /api/rest/v2/schemas/keyspaces/{keyspace_name}/tables/{table_name} to delete a table. All data will be deleted along with the table schema.

curl -s --location \
--request DELETE https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json"

Create an index

Tables can contain partition keys and clustering keys, both of which define the primary key. A table can also include non-primary keys.

If you wish to create a table query that uses anything other than the partition key to define which row or rows are to be retrieved, a column index must be created on each column to read the data.

Currently, those indexes can be created with REST, CQL, or GraphQL.

Send a POST request to /api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes to create an index. Set the index definitions in the JSON body in the --data. In this example, an index name is defined as fav_books_idx for the column favorite_books in the keyspace users_keyspace and table users. An option to only create the index if it already exists is set with ifNotExists: true; the default is false.

Two additional options are available:

  • type can be defined to use SAI indexes if desired; the default is secondary indexes.

  • kind defines the kind of index for map collections; the choices available are VALUES/KEYS/ENTRIES/FULL.

  • cURL command (/v2)

  • Result

curl -s --location \
--request POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
  "column": "favorite_books",
  "name": "fav_books_idx",
  "ifNotExists": true
}'
{
  "success": true
}

Here is an additional example, which creates indexes that are used in the REST API examples:

  • cURL command

  • Result

curl -s --location \
--request POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
  "column": "favorite_books",
  "name": "fav_books_idex",
  "ifNotExists": true
}'

curl -s --location \
--request POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
  "column": "top_three_tv_shows",
  "name": "tv_idx",
  "ifNotExists": true
}'

curl -s --location \
--request POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
  "column": "evaluations",
  "name": "evalv_idx",
  "ifNotExists": true
}'

curl -s --location \
--request POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
  "column": "evaluations",
  "name": "evalk_idx",
  "kind": "KEYS",
  "ifNotExists": true
}'

curl -s --location \
--request POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
  "column": "evaluations",
  "name": "evale_idx",
  "kind": "ENTRIES",
  "ifNotExists": true
}'

curl -s --location \
--request POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
  "column": "current_country",
  "name": "country_idx",
  "ifNotExists": true
}'
{
  "success": true
}
{
  "success": true
}
{
  "success": true
}
{
  "success": true
}
{
  "success": true
}
{
  "success": true
}

Note the use of the kind in the definitions used for the map collection evaluations.

Delete an index

You may wish to list all the indexes to verify the index name you wish to delete:

  • cURL command (/v2)

  • Result

curl -s --location \
--request GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
[
  {
    "keyspace_name": "users_keyspace",
    "options": [
      {
        "key": "target",
        "value": "current_country"
      }
    ],
    "table_name": "users",
    "index_name": "country_idx",
    "kind": "COMPOSITES"
  },
  {
    "keyspace_name": "users_keyspace",
    "options": [
      {
        "key": "target",
        "value": "entries(evaluations)"
      }
    ],
    "table_name": "users",
    "index_name": "evale_idx",
    "kind": "COMPOSITES"
  },
  {
    "keyspace_name": "users_keyspace",
    "options": [
      {
        "key": "target",
        "value": "keys(evaluations)"
      }
    ],
    "table_name": "users",
    "index_name": "evalk_idx",
    "kind": "COMPOSITES"
  },
  {
    "keyspace_name": "users_keyspace",
    "options": [
      {
        "key": "target",
        "value": "values(evaluations)"
      }
    ],
    "table_name": "users",
    "index_name": "evalv_idx",
    "kind": "COMPOSITES"
  },
  {
    "keyspace_name": "users_keyspace",
    "options": [
      {
        "key": "target",
        "value": "values(favorite_books)"
      }
    ],
    "table_name": "users",
    "index_name": "fav_books_idx",
    "kind": "COMPOSITES"
  },
  {
    "keyspace_name": "users_keyspace",
    "options": [
      {
        "key": "target",
        "value": "values(top_three_tv_shows)"
      }
    ],
    "table_name": "users",
    "index_name": "tv_idx",
    "kind": "COMPOSITES"
  }
]

Send a DELETE request to /api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes/{index_name} to delete an index. All index data will be deleted along with the index schema.

curl -s --location \
--request DELETE https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/indexes/fav_books_idx \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--header "Accept: application/json"

If the call is successful, a 204 message is returned.

Create a user-defined type (UDT)

A user-defined type, or UDT, consists of two or more values that can be retrieved together. UDTs are useful for associating items that are naturally grouped, like an address (street, city, zip code), or a review (item reviewed, rating, date reviewed).

UDTs are stored in a defined keyspace and can be used in other UDT definitions or table columns.

Send a POST request to /api/rest/v2/schemas/keyspaces{keyspace_name}/types. In this example we use address_type for the name. The defined fields describe the included items and their data type.

  • cURL command (/v2)

  • Result

curl -s -L -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/types \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H 'Content-Type: application/json' \
-d '{
  "name": "address_type",
  "fields":[
    {
      "name": "street",
      "typeDefinition": "text"
    },
    {
      "name": "city",
      "typeDefinition": "text"
    },
    {
      "name": "state",
      "typeDefinition": "text"
    },
    {
      "name": "zip",
      "typeDefinition": "text"
    }
  ]
}'
{
    "name": "address_type"
}

Delete a UDT

To delete a UDT, use a DELETE request to /api/rest/v2/schemas/keyspaces/{keyspace_name}/types/{type_name}. All UDT schema will be deleted along with the UDT data.

  • cURL command (/v2)

curl --location --request DELETE https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/types/address_type \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header 'Content-Type: application/json'

Add columns to table schema

If you need to add an attribute to something you are storing in a table, you can add a column by sending a POST request to add the column.

  • cURL command (/v2)

  • Result

curl -s -L -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
   "name": "email",
   "typeDefinition": "text"
}'
{ "name": "email" }

To change the name or data type of an existing column, use a similar command, but sent a PUT request instead:

  • cURL command (/v2)

  • Result

curl -s -L \
-X PUT https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns/firstname \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{   "name": "first",   "typeDefinition": "varchar"}'
{
  "name": "first"
}

To add a set to a table, specify the data type set along with the data type of the set contents, such as text:

  • cURL command (/v2)

  • Result

curl -s -L -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
   "name": "favorite_books",
   "typeDefinition": "set<text>"
}'
{"name":"favorite_books"}

To add a set as a frozen set, specify "typeDefinition": "frozen<set<text>>" with the keyword frozen. In the following examples, both lists and maps can also be specified as frozen.

To add a list to a table, specify the data type list along with the data type of the set contents, such as text. The difference between a set and a list is that a set is unordered, whereas a list is ordered:

  • cURL command (/v2)

  • Result

curl -s -L -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
   "name": "top_three_tv_shows",
   "typeDefinition": "list<text>"
}'
{"name":"top_three_tv_shows"}

To add a map to a table, specify the data type map along with the data type of the map key and the may value:

  • cURL command (/v2)

  • Result

curl -s -L -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
   "name": "evaluations",
   "typeDefinition": "map<int,text>"
}'
{"name":"evaluations"}

To add a tuple to a table, specify the data type tuple along with the data type of the each item in the tuple. A tuple can consist of two or more values that can be retrieved together.

  • cURL command (/v2)

  • Result

curl -s -L -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
   "name": "current_country",
   "typeDefinition": "tuple<text, date, date>"
}'
{"name":"current_country"}

To add a user-defined type (UDT) to a table, specify the data type udt along with the data type of the each item in the UDT. A UDT can consist of two or more values that can be retrieved together.

UDTs must currently be created in CQL before specifying for a column in the REST API. For instance, for a UDT created with the following CQL statement:

CREATE TYPE IF NOT EXISTS users_keyspace.address (
  street text,
  zip int
);

we can add a UDT column to our table:

  • cURL command (/v2)

  • Result

curl -s -L -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
   "name": "address",
   "typeDefinition": "address_type"
}'
{ "name": "address" }

To check if a column exists, execute a REST API query with cURL to find all the columns:

  • cURL command (/v2)

  • Result

curl -s -L \
-X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Accept: application/json" \
-H "Content-Type: application/json"
{
  "data": [
    {
      "name": "firstname",
      "typeDefinition": "varchar",
      "static": false
    },
    {
      "name": "lastname",
      "typeDefinition": "varchar",
      "static": false
    },
    {
      "name": "current_country",
      "typeDefinition": "frozen<tuple<varchar, date, date>>",
      "static": false
    },
    {
      "name": "email",
      "typeDefinition": "varchar",
      "static": false
    },
    {
      "name": "evaluations",
      "typeDefinition": "map<int, varchar>",
      "static": false
    },
    {
      "name": "favorite color",
      "typeDefinition": "varchar",
      "static": false
    },
    {
      "name": "favorite_books",
      "typeDefinition": "set<varchar>",
      "static": false
    },
    {
      "name": "top_three_tv_shows",
      "typeDefinition": "list<varchar>",
      "static": false
    }
  ]
}

To get a particular column, specify the column in the URL:

  • cURL command (/v2)

  • Result

curl -s -L \
-X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns/email \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json"
{
  "data":{
    "name":"email",
    "typeDefinition":"varchar",
    "static":false
  }
}

Delete columns from table schema

If you find an attribute is no longer required in a table, you can delete a column by sending a DELETE request. All column data will be deleted along with the column schema.

curl -s --location \
--request DELETE https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/tables/users/columns/email \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json"

Write data

First, let’s add some data to the users table that you created. Send a POST request to /v2/keyspaces/{keyspace_name}/{table_name} to add data to the table. The column name/value pairs are passed in the JSON body.

  • cURL command (/v2)

  • Result

curl -s --location --request POST 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users' \
--header "X-Cassandra-Token: $AUTH_TOKEN" \
--header 'Content-Type: application/json' \
--data '{
    "firstname": "Mookie",
    "lastname": "Betts",
    "email": "mookie.betts@gmail.com",
    "favorite color": "blue"
}'
curl -s --location --request POST 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users' \
--header "X-Cassandra-Token: $AUTH_TOKEN" \
--header 'Content-Type: application/json' \
--data '{
    "firstname": "Janesha",
    "lastname": "Doesha",
    "email": "janesha.doesha@gmail.com",
    "favorite color": "grey"
}'
{"firstname":"Mookie","lastname":"Betts"}
{"firstname":"Janesha","lastname":"Doesha"}

Notice that, unlike schema creation, data queries do not require tables in the URI, only the {tableName}.

Collections, tuples, and UDTs

Some data types require special handling to write the data. Examples of set, list, map, tuple, and udt are shown, using the column schema created earlier.

SET:

  • cURL command (/v2)

  • Result

curl -s -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
-H  "accept: application/json" \
-H  "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Content-Type: application/json" \
-d '{"firstname": "Janesha",
  "lastname": "Doesha",
  "favorite color": "grey",
  "favorite_books": [ "Emma", "The Color Purple" ]
}'
{"firstname":"Janesha","lastname":"Doesha"}

LIST:

  • cURL command (/v2)

  • Result

curl -s -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
-H  "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Content-Type: application/json" \
-H  "Accept: application/json" \
-d '{"firstname": "Janesha",
  "lastname": "Doesha",
  "favorite color": "grey",
  "top_three_tv_shows": [ "The Magicians", "The Librarians", "Agents of SHIELD" ]
}'
{"firstname":"Janesha","lastname":"Doesha"}

MAP:

  • cURL command (/v2)

  • Result

curl -s -L -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
-H  "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H  "Content-Type: application/json" \
-H  "Accept: application/json" \
-d '{"firstname": "Janesha",
  "lastname": "Doesha",
  "favorite color": "grey",
  "top_three_tv_shows": [ "The Magicians", "The Librarians", "Agents of SHIELD" ],
  "evaluations": [ {"key":"2020", "value":"good"}, {"key":"2019", "value":"okay"} ]
}'
{"firstname":"Janesha","lastname":"Doesha"}

TUPLE:

  • cURL command (/v2)

  • Result

curl -s -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
-H  "accept: application/json" \
-H  "X-Cassandra-Token: $AUTH_TOKEN" \
-H  "Content-Type: application/json" \
-d '{"firstname": "Janesha",
  "lastname": "Doesha",
  "favorite color": "grey",
  "current_country": [ "France", "2016-01-01", "2020-02-02" ]
}'
{"firstname":"Janesha","lastname":"Doesha"}

UDT:

  • cURL command (/v2)

  • Result

curl -s -X POST https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
-H  "accept: application/json" \
-H  "X-Cassandra-Token: $AUTH_TOKEN" \
-H  "Content-Type: application/json" \
-d '{"firstname": "Janesha",
  "lastname": "Doesha",
  "favorite color": "grey",
  "address": { "street": "1 Main St", "zip": "12345" }
}'
{"firstname":"Janesha","lastname":"Doesha"}

Read data

Let’s check that the data was inserted. Send a GET request to /v2/keyspaces/{keyspace_name}/{table_name}?where={searchPath} to retrieve the two users that were entered:

  • cURL command (/v2)

  • Result

curl -s -L -X GET 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users?where=\{"firstname":\{"$in":\["Janesha","Mookie"\]\}\}' \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json"
{
  "count": 2,
  "data": [
    {
      "firstname": "Janesha",
      "evaluations": [
        {
          "key": 2019,
          "value": "okay"
        },
        {
          "key": 2020,
          "value": "good"
        }
      ],
      "top_three_tv_shows": [
        "The Magicians",
        "The Librarians",
        "Agents of SHIELD"
      ],
      "favorite color": "grey",
      "current_country": [
        "France",
        {
          "year": 2016,
          "month": "JANUARY",
          "dayOfMonth": 1,
          "dayOfWeek": "FRIDAY",
          "era": "CE",
          "dayOfYear": 1,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 1
        },
        {
          "year": 2020,
          "month": "FEBRUARY",
          "dayOfMonth": 2,
          "dayOfWeek": "SUNDAY",
          "era": "CE",
          "dayOfYear": 33,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 2
        }
      ],
      "email": "janesha.doesha@gmail.com",
      "lastname": "Doesha",
      "favorite_books": [
        "Emma",
        "The Color Purple"
      ]
    },
    {
      "firstname": "Mookie",
      "evaluations": [],
      "top_three_tv_shows": [],
      "favorite color": "blue",
      "current_country": null,
      "email": "mookie.betts.new-email@email.com",
      "lastname": "Betts",
      "favorite_books": []
    }
  ]
}

This query uses $in to find the two users. The WHERE clause can be used with other valid search terms: $eq, $lt, $lte, $gt, $gte, $ne, and $exists, if applicable. The primary key of the table can be used in the WHERE clause, but non-primary key columns cannot be used unless indexed.

Send a GET request to /v2/keyspaces/{keyspace_name}/{table_name} to retrieve the row for Mookie using $eq:

  • cURL command (/v2)

  • Result

curl -s -L -X GET 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users?where=\{"firstname":\{"$eq":"Mookie"\}\}' \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json"
{
  "count": 1,
  "data": [
    {
      "firstname": "Mookie",
      "evaluations": [],
      "top_three_tv_shows": [],
      "favorite color": "blue",
      "current_country": null,
      "email": "mookie.betts.new-email@email.com",
      "lastname": "Betts",
      "favorite_books": []
    }
  ]
}

If the CQL indexes exist, a multiple WHERE can be used:

Send a GET request to /v2/keyspaces/{keyspace_name}/{table_name} to retrieve the row for Janesha using $eq, and Emma using $contains:

  • cURL command (/v2)

  • Result

curl -s -L -X GET 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users?where=\{"firstname":\{"$eq":"Janesha"\},"favorite_books":\{"$contains":"Emma"\}\}' \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json"
{
  "count": 1,
  "data": [
    {
      "firstname": "Janesha",
      "evaluations": [
        {
          "key": 2019,
          "value": "okay"
        },
        {
          "key": 2020,
          "value": "good"
        }
      ],
      "top_three_tv_shows": [
        "The Magicians",
        "The Librarians",
        "Agents of SHIELD"
      ],
      "favorite color": "grey",
      "current_country": [
        "France",
        {
          "year": 2016,
          "month": "JANUARY",
          "dayOfMonth": 1,
          "dayOfWeek": "FRIDAY",
          "era": "CE",
          "dayOfYear": 1,
          "leapYear": true,
          "monthValue": 1,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          }
        },
        {
          "year": 2020,
          "month": "FEBRUARY",
          "dayOfMonth": 2,
          "dayOfWeek": "SUNDAY",
          "era": "CE",
          "dayOfYear": 33,
          "leapYear": true,
          "monthValue": 2,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          }
        }
      ],
      "email": "janesha.doesha@gmail.com",
      "lastname": "Doesha",
      "favorite_books": [
        "Emma",
        "The Color Purple"
      ]
    }
  ]
}

A primary key can be supplied to retrieve a row:

  • cURL command (/v2)

  • Result

curl -s -L -X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users/Mookie/Betts \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json"
{
  "count": 1,
  "data": [
    {
      "firstname": "Mookie",
      "evaluations": [],
      "top_three_tv_shows": [],
      "favorite color": "blue",
      "current_country": null,
      "email": "mookie.betts.new-email@email.com",
      "lastname": "Betts",
      "favorite_books": []
    }
  ]
}

Adding /rows instead of a WHERE clause or primary key returns all table rows.

Returning all rows in a large table can negatively impact your database. The page-size parameter limits the number of results returned, and is recommended for large tables. The pageState is useful for pagination of the results in queries.
  • cURL command (/v2)

  • Result

curl -s -L -X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users/rows \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json"
{
  "count": 2,
  "data": [
    {
      "firstname": "Mookie",
      "evaluations": [],
      "top_three_tv_shows": [],
      "favorite color": "blue",
      "current_country": null,
      "email": "mookie.betts.new-email@email.com",
      "lastname": "Betts",
      "favorite_books": []
    }, 
    {
      "firstname": "Janesha",
      "evaluations": [
        {
          "key": 2019,
          "value": "okay"
        },
        {
          "key": 2020,
          "value": "good"
        }
      ],
      "top_three_tv_shows": [
        "The Magicians",
        "The Librarians",
        "Agents of SHIELD"
      ],
      "favorite color": "grey",
      "current_country": [
        "France",
        {
          "year": 2016,
          "month": "JANUARY",
          "dayOfMonth": 1,
          "dayOfWeek": "FRIDAY",
          "era": "CE",
          "dayOfYear": 1,
          "leapYear": true,
          "monthValue": 1,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          }
        },
        {
          "year": 2020,
          "month": "FEBRUARY",
          "dayOfMonth": 2,
          "dayOfWeek": "SUNDAY",
          "era": "CE",
          "dayOfYear": 33,
          "leapYear": true,
          "monthValue": 2,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          }
        }
      ],
      "email": "janesha.doesha@gmail.com",
      "lastname": "Doesha",
      "favorite_books": [
        "Emma",
        "The Color Purple"
      ]
    }
  ]
}

In this example both Mookie and Betts are supplied in the path. Mookie is the partition key firstname and Betts is the clustering key lastname. Together these keys form the primary key of a row. To retrieve any rows using the partition keys and clustering keys, the primary key can be part of the request, in order and separated by a forward slash, such as pk1/pk2/ck1/ck2/…​. Each key must be included in order, but subsequent clustering keys do not have to be included. Note that the inclusion of clustering keys may return a range of rows.

To return only desired fields in a response object, use the fields query parameter:

  • cURL command (/v2)

  • Result

curl -s -L -X GET https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users/Janesha/Doesha?fields=firstname,lastname,top_three_tv_shows \
--header "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json"
{
  "count": 1,
  "data": [
    {
      "firstname": "Janesha",
      "lastname": "Doesha",
      "top_three_tv_shows": [
        "The Magicians",
        "The Librarians",
        "Agents of SHIELD"
      ]
    }
  ]
}

Collections, tuples, and UDTs

Some data types require special handling to read the data. Examples of set, list, map, tuple, and udt are shown, using the column schema created earlier. Because these columns are not part of the partition or clustering key, an index is required to read the data. Currently, for Cassandra, those indexes must be created with CQL. Here are the indexes created for use in the following examples:

CREATE INDEX books_idx ON users_keyspace.users (VALUES(favorite_books));
CREATE INDEX tv_idx ON users_keyspace.users (VALUES (top_three_tv_shows));
CREATE INDEX evalk_idx ON users_keyspace.users (KEYS (evaluations));
CREATE INDEX evalv_idx ON users_keyspace.users (VALUES (evaluations));
CREATE INDEX evale_idx ON users_keyspace.users (ENTRIES (evaluations));
CREATE INDEX country_idx ON users_keyspace.users (VALUES (current_country));

If you are using DataStax Enterprise, you may optionally use Storage-Attached Indexing (SAI):

CREATE CUSTOM INDEX books_idx 
  ON users_keyspace.users (VALUES(favorite_books)) 
  USING 'StorageAttachedIndex'
  WITH OPTIONS = ('case_sensitive': 'false');
CREATE CUSTOM INDEX tv_idx
  ON users_keyspace.users (VALUES(top_three_tv_shows))
  USING 'StorageAttachedIndex'
  WITH OPTIONS = ('case_sensitive': 'false');
CREATE CUSTOM INDEX eval_idx
  ON users_keyspace.users (KEYS(evaluations))
  USING 'StorageAttachedIndex'
  WITH OPTIONS = ('case_sensitive': 'false');

SAI does not support tuples. Searches using SAI do not support the operator $in.

SET:

  • cURL command (/v2)

  • Result

curl -s -L -G https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
   -H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
   -H "Content-Type: application/json" \
   -H "Accept: application/json" \
   --data-urlencode 'where={
     "firstname": {"$eq": "Janesha"},
     "lastname": {"$eq": "Doesha"},
     "favorite_books": {"$contains": "Emma"}
   }'
{
  "count": 1,
  "data": [
    {
      "firstname": "Janesha",
      "evaluations": [
        {
          "key": 2019,
          "value": "okay"
        },
        {
          "key": 2020,
          "value": "good"
        }
      ],
      "top_three_tv_shows": [
        "The Magicians",
        "The Librarians",
        "Agents of SHIELD"
      ],
      "favorite color": "grey",
      "current_country": [
        "France",
        {
          "year": 2016,
          "month": "JANUARY",
          "dayOfMonth": 1,
          "dayOfWeek": "FRIDAY",
          "era": "CE",
          "dayOfYear": 1,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 1
        },
        {
          "year": 2020,
          "month": "FEBRUARY",
          "dayOfMonth": 2,
          "dayOfWeek": "SUNDAY",
          "era": "CE",
          "dayOfYear": 33,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 2
        }
      ],
      "email": "janesha.doesha@gmail.com",
      "lastname": "Doesha",
      "favorite_books": [
        "Emma",
        "The Color Purple"
      ]
    }
  ]
}

LIST:

  • cURL command (/v2)

  • Result

curl -s -L -G https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
   -H  "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
   -H  "Content-Type: application/json" \
   -H "Accept: application/json" \
   --data-urlencode 'where={
     "firstname": {"$eq": "Janesha"},
     "lastname": {"$eq": "Doesha"},
     "top_three_tv_shows": {"$contains": "The Magicians"}
   }'
{
  "count": 1,
  "data": [
    {
      "firstname": "Janesha",
      "evaluations": [
        {
          "key": 2019,
          "value": "okay"
        },
        {
          "key": 2020,
          "value": "good"
        }
      ],
      "top_three_tv_shows": [
        "The Magicians",
        "The Librarians",
        "Agents of SHIELD"
      ],
      "favorite color": "grey",
      "current_country": [
        "France",
        {
          "year": 2016,
          "month": "JANUARY",
          "dayOfMonth": 1,
          "dayOfWeek": "FRIDAY",
          "era": "CE",
          "dayOfYear": 1,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 1
        },
        {
          "year": 2020,
          "month": "FEBRUARY",
          "dayOfMonth": 2,
          "dayOfWeek": "SUNDAY",
          "era": "CE",
          "dayOfYear": 33,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 2
        }
      ],
      "email": "janesha.doesha@gmail.com",
      "lastname": "Doesha",
      "favorite_books": [
        "Emma",
        "The Color Purple"
      ]
    }
  ]
}

MAP:

  • cURL command (/v2)

  • Result

curl -s -L -G https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
   -H  "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
   -H  "Content-Type: application/json" \
    -H "Accept: application/json" \
   --data-urlencode 'where={
     "firstname": {"$eq": "Janesha"},
     "lastname": {"$eq": "Doesha"},
     "evaluations": {"$containsKey": "2020"}
   }'
{
  "count": 1,
  "data": [
    {
      "firstname": "Janesha",
      "evaluations": [
        {
          "key": 2019,
          "value": "okay"
        },
        {
          "key": 2020,
          "value": "good"
        }
      ],
      "top_three_tv_shows": [
        "The Magicians",
        "The Librarians",
        "Agents of SHIELD"
      ],
      "favorite color": "grey",
      "current_country": [
        "France",
        {
          "year": 2016,
          "month": "JANUARY",
          "dayOfMonth": 1,
          "dayOfWeek": "FRIDAY",
          "era": "CE",
          "dayOfYear": 1,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 1
        },
        {
          "year": 2020,
          "month": "FEBRUARY",
          "dayOfMonth": 2,
          "dayOfWeek": "SUNDAY",
          "era": "CE",
          "dayOfYear": 33,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 2
        }
      ],
      "email": "janesha.doesha@gmail.com",
      "lastname": "Doesha",
      "favorite_books": [
        "Emma",
        "The Color Purple"
      ]
    }
  ]
}

TUPLE:

  • cURL command (/v2)

  • Result

curl -s -G -L https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
   -H  "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
   -H  "Content-Type: application/json" \
   --data-urlencode 'where={
     "firstname": {"$eq": "Janesha"},
     "lastname": {"$eq": "Doesha"},
     "current_country": {"$eq": "( 'France', '2016-01-01', '2020-02-02' )"}
   }'
{
  "count": 1,
  "data": [
    {
      "firstname": "Janesha",
      "evaluations": [
        {
          "key": 2019,
          "value": "okay"
        },
        {
          "key": 2020,
          "value": "good"
        }
      ],
      "top_three_tv_shows": [
        "The Magicians",
        "The Librarians",
        "Agents of SHIELD"
      ],
      "favorite color": "grey",
      "current_country": [
        "France",
        {
          "year": 2016,
          "month": "JANUARY",
          "dayOfMonth": 1,
          "dayOfWeek": "FRIDAY",
          "era": "CE",
          "dayOfYear": 1,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 1
        },
        {
          "year": 2020,
          "month": "FEBRUARY",
          "dayOfMonth": 2,
          "dayOfWeek": "SUNDAY",
          "era": "CE",
          "dayOfYear": 33,
          "leapYear": true,
          "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
          },
          "monthValue": 2
        }
      ],
      "email": "janesha.doesha@gmail.com",
      "lastname": "Doesha",
      "favorite_books": [
        "Emma",
        "The Color Purple"
      ]
    }
  ]
}

UDT:

  • cURL command (/v2)

  • Result

curl -s -L -G https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users \
   -H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
   -H "Content-Type: application/json" \
   -H "Accept: application/json" \
   --data-urlencode 'where={
     "firstname": {"$eq": "Janesha"},
     "lastname": {"$eq": "Doesha"},
     "address": {\"$eq\": { \"street\": \"1, Main St\", \"zip\": 12345 }}
   }'
Example coming

Update data

Data changes, so often it is necessary to update an entire row. To update a row, send a PUT request to /v2/keyspaces/{keyspace_name}/{table_name}/{path}. The {path} is comprised of the primary key values. In this example, the partition key is firstname "Mookie" and the clustering key is lastname "Betts"; thus, we use /Mookie/Betts as the {path} in our request.

  • cURL command (/v2)

  • Result

curl -s -L -X PUT 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users/Mookie/Betts' \
-H "X-Cassandra-Token: $AUTH_TOKEN" \
-H 'Content-Type: application/json' \
-d '{
    "email": "mookie.betts.new-email@email.com"
}'
{"data":{"email":"mookie.betts.new-email@email.com"}}

Updates are upserts. If the row doesn’t exist, it will be created. If it does exist, it will be updated with the new row data.

It is also possible to update only part of a row. To partially update, send a PATCH request to /v2/keyspaces/{keyspace_name}/{table_name}/{path}. In this example, we realize we should not have changed the email address, and we want to only change that one column:

  • cURL command (/v2)

  • Result

curl -s -L -X PATCH 'https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users/Mookie/Betts' \
-H "X-Cassandra-Token: $AUTH_TOKEN" \
-H 'Content-Type: application/json' \
-d '{
    "email": "mookie.betts.email@email.com"
}'
{"data":{"email":"mookie.betts.email@email.com"}}

Delete data

To delete a row, send a DELETE request to /v2/keyspaces/{keyspace_name}/{table_name}/{primaryKey}. For this example, the primary key consists of a partition key firstname and clustering column lastname, so we delete all data with Mookie/Betts:

curl -s -L -X DELETE https://$ASTRA_CLUSTER_ID-$ASTRA_REGION.apps.astra.datastax.com/api/rest/v2/schemas/keyspaces/users_keyspace/users/Mookie/Betts \
-H "X-Cassandra-Token: $ASTRA_DB_APPLICATION_TOKEN" \
-H "Content-Type: application/json"

REST API Software Development Kit (SDK)

Node.js can be used with Astra to programmatically interact with your data using the REST API. An example of a client to work with collections is shown below.

First, set up your environment:

Node.js REST Client

Connect your app to DataStax Astra DB using a REST interface from node.js.

The Astra DB REST Client connects to the Astra DB REST API and the Astra DB Document API.

Set up your environment

  1. Install the Astra DB JS Collection:

    npm install @astrajs/rest
  2. Open a browser, navigate to Astra DB, and log in.

  3. From your Dashboard page, select your database.

  4. Copy the Cluster ID of your database. You can also find the Cluster ID in the URL, which is the last UUID in the path:

    https://astra.datastax.com/org/{org-Id}/database/{databaseid}
  5. Add the Cluster ID as an environment variable with the following command:

    export ASTRA_DB_ID={databaseid}

    Example

    export ASTRA_DB_ID=b5285f63-8da5-4c6e-afd8-ade371a48795
  6. Copy the Region of your database, the region where your database is located.

  7. Add the Region as an environment variable with the following command:

    export ASTRA_DB_REGION={region}

    Example

    export ASTRA_DB_REGION=us-east1
  8. Add your application token as environment variables with the following command:

    export ASTRA_DB_APPLICATION_TOKEN={token}
  9. Use printenv to ensure the environment variables were exported.

And then create a client:

Node.js REST Client

  const { createClient } = require("@astrajs/rest");

  // create an Astra client
  const astraClient = await createClient({
      astraDatabaseId: process.env.ASTRA_DB_ID,
      astraDatabaseRegion: process.env.ASTRA_DB_REGION,
      username: process.env.ASTRA_DB_USERNAME,
      password: process.env.ASTRA_DB_PASSWORD,
  });

  const basePath = "/api/rest/v2/KEYSPACES/<namespace>/collections/<collectionName>";

  // get a single user by document id
  const { data, status } = await astraClient.get(`${basePath}/<documentId>`);

  // get a subdocument by path
  const { data, status } = await astraClient.get(`${basePath}/<documentId>/<subdocument>/<subdocument>`);

  // search a collection of documents
  const { data, status } = await astraClient.get(${basePath}, {
    params: {
      where: {
        name: { $eq: "<documentId>" }
      }
    }
  });

  // create a new user without a document id
  ----
  const { data, status } = await astraClient.post(${basePath}, {
    name: "<documentId>",
  });
  ----

  // create a new user with a document id
  const { data, status } = await astraClient.put(`${basePath}/<documentId>`, {
    name: "cliff",
  });

  // create a user subdocument
  const { data, status } = await astraClient.put(`${basePath}/<documentId>/<subdocument>`, {
    title: "new blog",
  });

  // partially update user
  const { data, status } = await astraClient.patch(`${basePath}/<documentId>`, {
    name: "cliff",
  });

  // delete a user
  const { data, status } = await astraClient.delete(`${basePath}/<documentId>`);