Skip to main content

Official Python SDK for Contextbase API

Project description

Contextbase Python SDK

Python Version License

The official Python SDK for Contextbase

Installation

pip install contextbase

Quick start

Setup

First, set your API key as an environment variable:

export CONTEXTBASE_API_KEY="your-api-key-here"

Or pass it directly when initializing the client:

from contextbase import Contextbase

client = Contextbase(api_key="your-api-key-here")

Basic usage

Publishing JSON data

from contextbase import Contextbase

cb = Contextbase()

# Publish JSON data
response = cb.publish(
    context_name="my-app",
    component_name="user-analytics", 
    body={"action": "login", "timestamp": "2024-01-15T10:30:00Z"},
    scopes={"user_id": 123}
)

if response.ok:
    print("Data published successfully!")
    print(f"Response: {response.json}")
else:
    print(f"Error: {response.error.message}")

Publishing files

from contextbase import Contextbase, ContextbaseFile

cb = Contextbase()

# Method 1: Use the convenience method
response = cb.publish_file(
    context_name="documents",
    component_name="reports",
    file_path="report.pdf"
)

# Method 2: Create file from path
file = ContextbaseFile.from_path("path/to/your/document.pdf")
response = cb.publish(
    context_name="documents",
    component_name="reports",
    file=file
)

# Method 3: Create from data content
content = "Daily report: All systems operational!"
file = ContextbaseFile.from_data(content, "daily-report.txt")
response = cb.publish(
    context_name="reports",
    component_name="daily",
    file=file
)

# Method 4: Create from binary data
with open("image.png", "rb") as f:
    binary_data = f.read()
file = ContextbaseFile.from_data(binary_data, "screenshot.png")
response = cb.publish(
    context_name="images",
    component_name="screenshots",
    file=file
)

Resolving context

# Basic query
response = client.resolve("my-app")

# Query with search term
response = client.resolve(
    context_name="my-app",
    query="user login events"
)

# Query with scopes
response = client.resolve(
    context_name="my-app",
    scopes={"environment": "production", "date_range": "last_week"}
)

if response.ok:
    print(f"Resolved context response: {response.json}")

Using the decorator

The @publish decorator automatically publishes function results to Contextbase:

For JSON data

from contextbase import publish

@publish(context_name="ml-models", component_name="predictions")
def predict_user_behavior(user_data):
    # Your ML logic here
    prediction = {"user_id": user_data["id"], "likely_to_churn": 0.23}
    return prediction

# Function runs normally, and result is automatically published
result = predict_user_behavior({"id": 123, "activity": "low"})

For file output

# Automatically upload function output as a file
@publish(
    context_name="reports", 
    component_name="daily-summary",
    as_file=True,
    file_name="summary.txt"
)
def generate_daily_report():
    return "Daily Summary: All systems operational!"

# Content is automatically converted to ContextbaseFile and uploaded
report = generate_daily_report()

# Works with binary data too
@publish(
    context_name="images",
    component_name="generated-charts", 
    as_file=True,
    file_name="chart.png"
)
def create_chart():
    # Return binary PNG data
    return generate_png_bytes()

Decorator with error handling

# Raise exceptions on publish failures
@publish(
    context_name="critical-data", 
    component_name="financial-calculations",
    raise_on_error=True
)
def calculate_risk_score(portfolio):
    return {"risk_score": 0.75, "confidence": 0.92}

# Silently continue on publish failures (default)
@publish(
    context_name="analytics", 
    component_name="user-events",
    raise_on_error=False
)
def track_user_action(user_id, action):
    return {"user_id": user_id, "action": action}

Decorator with scopes

@publish(
    context_name="monitoring",
    component_name="system-metrics",
    scopes={"environment": "production", "service": "api"}
)
def collect_metrics():
    return {
        "cpu_usage": 45.2,
        "memory_usage": 67.8,
        "timestamp": "2024-01-15T10:30:00Z"
    }

Advanced usage

Error handling

from contextbase import Contextbase, ContextbaseError

client = Contextbase()

try:
    response = client.publish("context", "component", body={"data": "value"})
    response.raise_for_status()  # Raises ContextbaseError if response failed
    print("Success!")
except ContextbaseError as e:
    print(f"API Error: {e.message}")
    print(f"Status Code: {e.status_code}")
    for error in e.errors:
        print(f"  - {error}")
except Exception as e:
    print(f"Unexpected error: {e}")

Response object methods

response = client.publish("context", "component", body={"data": "value"})

# Check success
if response.ok:  # or response.is_success
    print("Request successful")

# Access response data
data = response.json          # Parsed JSON response
text = response.text          # Raw response text  
headers = response.headers    # Response headers dict

# Dict-like access
value = response.get("key", "default")
if "field" in response:
    field_value = response["field"]

# Error information
if not response.ok:
    error = response.error
    print(f"Error: {error.message}")
    print(f"Details: {error.errors}")

File upload reference

ContextbaseFile class

The ContextbaseFile class provides an interface for file publishing:

from contextbase import ContextbaseFile

# Create from file path
file = ContextbaseFile.from_path("document.pdf")

# Create from string content
file = ContextbaseFile.from_data("Hello World", "greeting.txt")

# Create from binary content  
with open("image.png", "rb") as f:
    binary_data = f.read()
file = ContextbaseFile.from_data(binary_data, "image.png")

# Create with explicit MIME type
file = ContextbaseFile.from_data(
    content="Custom content",
    name="data.custom",
    mime_type="application/custom"
)

# Direct constructor
import base64
file = ContextbaseFile(
    name="file.txt",
    mime_type="text/plain",
    base64_content=base64.b64encode(b"content").decode()
)

# Access file properties
print(file.name)           # "file.txt"
print(file.mime_type)      # "text/plain"
print(file.get_content())  # b"content"
print(file.get_size())     # 7

Supported file types

See documentation

Error reference

ContextbaseError

Raised when the API returns an error response:

try:
    response = client.publish("context", "component", body={})
    response.raise_for_status()
except ContextbaseError as e:
    print(f"Status: {e.status_code}")     # HTTP status code
    print(f"Message: {e.message}")        # Error message
    print(f"Details: {e.errors}")         # List of detailed errors

Development

Running tests

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=contextbase --cov-report=html

# Run specific test file
pytest tests/test_file_upload.py -v

Support

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

contextbase-1.0.4.tar.gz (21.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

contextbase-1.0.4-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file contextbase-1.0.4.tar.gz.

File metadata

  • Download URL: contextbase-1.0.4.tar.gz
  • Upload date:
  • Size: 21.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.6

File hashes

Hashes for contextbase-1.0.4.tar.gz
Algorithm Hash digest
SHA256 0c211531bbae51f687460610c0836a2af4f56c35e4186298f3406703e45a55fa
MD5 db30a2c185c3965e92bb1e50b9e3757f
BLAKE2b-256 b0bf127b953fde25d9eb383f5023683fd5643da34c28d23064cb5a3bacb9456c

See more details on using hashes here.

File details

Details for the file contextbase-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: contextbase-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.6

File hashes

Hashes for contextbase-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 50932dc53acd561fe7dd6a5d61c7154e6d9a0221f8ce3c623b649d3ad80c1c97
MD5 17e4e1ce1ee2cf417d12b3066ec86eac
BLAKE2b-256 9f20effb38080b43e034754ec5e0d97df85a51feea30f0f8060bb4d92c0d2cce

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page