Astrapy Python Client

2.2.1 · active · verified Mon Apr 13

Astrapy is a Python client library for interacting with the Data API on DataStax Astra DB. It provides a straightforward interface for working with both document collections (JSON) and tables. Currently at version 2.2.1, the library sees active development with frequent minor releases introducing new features and improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to DataStax Astra DB, get a collection, insert a document, and retrieve it. It relies on environment variables for secure credential management.

import os
from astrapy.db import AstraDB

# Get credentials from environment variables
ASTRA_DB_API_ENDPOINT = os.environ.get('ASTRA_DB_API_ENDPOINT', '')
ASTRA_DB_APPLICATION_TOKEN = os.environ.get('ASTRA_DB_APPLICATION_TOKEN', '')
ASTRA_DB_KEYSPACE = os.environ.get('ASTRA_DB_KEYSPACE', None) # Optional

if not ASTRA_DB_API_ENDPOINT or not ASTRA_DB_APPLICATION_TOKEN:
    raise ValueError(
        "Please set ASTRA_DB_API_ENDPOINT and ASTRA_DB_APPLICATION_TOKEN "
        "environment variables."
    )

# Initialize Astra DB client
astradb = AstraDB(
    api_endpoint=ASTRA_DB_API_ENDPOINT,
    token=ASTRA_DB_APPLICATION_TOKEN,
    namespace=ASTRA_DB_KEYSPACE,
)

print(f"Connected to Astra DB: {astradb.api_endpoint}")

# Get or create a collection
collection = astradb.collection("my_test_collection")

# Insert a document
document_id = "doc1"
inserted_document = collection.insert_one({"_id": document_id, "item": "apple", "price": 1.0})
print(f"Inserted document with ID: {inserted_document['inserted_id']}")

# Find a document
found_document = collection.find_one({"_id": document_id})
print(f"Found document: {found_document}")

# Clean up (optional)
# collection.delete_one({"_id": document_id})
# print(f"Deleted document with ID: {document_id}")

view raw JSON →