Skip to main content

API Authentication

Secure setup and credential management for the Carbon Arc SDK.


Getting Your API Token

  1. Log in to the Carbon Arc dashboard
  2. Navigate to User Portal → Profile
  3. Generate a new API token (if needed)
  4. Copy and store securely
warning

API tokens expire after 12 months and must be regenerated upon expiration.


Authentication Methods

Method 1: Direct Initialization (Quick Testing Only)

from carbonarc import CarbonArcClient

client = CarbonArcClient(
host="https://api.carbonarc.co",
token="YOUR_API_TOKEN" # Replace with your actual token
)

# Verify connection
try:
datasets = client.data.get_datasets()
print("Authentication successful!")
except Exception as e:
print(f"Authentication failed: {e}")

Set these in your shell or CI/CD pipeline:

export CARBONARC_TOKEN="your_token_here"
export CARBONARC_HOST="https://api.carbonarc.co"

Then in Python:

import os
from carbonarc import CarbonArcClient

TOKEN = os.environ.get("CARBONARC_TOKEN")
HOST = os.environ.get("CARBONARC_HOST", "https://api.carbonarc.co")

if not TOKEN:
raise ValueError("CARBONARC_TOKEN environment variable not set")

client = CarbonArcClient(host=HOST, token=TOKEN)

Method 3: .env File (Local Development)

Create a .env file in your project root:

# .env
CARBONARC_TOKEN=your_token_here
CARBONARC_HOST=https://api.carbonarc.co
warning

Add .env to your .gitignore!

Install python-dotenv:

pip install python-dotenv

Then in Python:

from dotenv import load_dotenv
import os
from carbonarc import CarbonArcClient

load_dotenv() # Looks for .env in current directory

TOKEN = os.environ.get("CARBONARC_TOKEN")
HOST = os.environ.get("CARBONARC_HOST", "https://api.carbonarc.co")

if not TOKEN:
raise ValueError("CARBONARC_TOKEN not found in .env file")

client = CarbonArcClient(host=HOST, token=TOKEN)

Method 4: Configuration File (Complex Projects)

Create a config.yaml (keep token in env, host in config):

# config.yaml
carbonarc:
host: https://api.carbonarc.co
# token: Use CARBONARC_TOKEN env var instead!

Then in Python:

import yaml
import os
from carbonarc import CarbonArcClient

def load_client_from_config(config_path="config.yaml"):
"""Load client with config file for host, env var for token."""
with open(config_path, "r") as f:
config = yaml.safe_load(f)

host = config.get("carbonarc", {}).get("host", "https://api.carbonarc.co")
token = os.environ.get("CARBONARC_TOKEN")

if not token:
raise ValueError("CARBONARC_TOKEN environment variable required")

return CarbonArcClient(host=host, token=token)

client = load_client_from_config("config.yaml")

Method 5: Secrets Manager (Production/Cloud)

For production deployments, use your cloud provider's secrets manager.

AWS Secrets Manager

import boto3
from carbonarc import CarbonArcClient

def get_client_aws():
"""Load token from AWS Secrets Manager."""
client = boto3.client("secretsmanager")
response = client.get_secret_value(SecretId="carbonarc/api-token")
token = response["SecretString"]
return CarbonArcClient(host="https://api.carbonarc.co", token=token)

Google Cloud Secret Manager

from google.cloud import secretmanager
from carbonarc import CarbonArcClient

def get_client_gcp(project_id):
"""Load token from GCP Secret Manager."""
client = secretmanager.SecretManagerServiceClient()
name = f"projects/{project_id}/secrets/carbonarc-token/versions/latest"
response = client.access_secret_version(request={"name": name})
token = response.payload.data.decode("UTF-8")
return CarbonArcClient(host="https://api.carbonarc.co", token=token)

Azure Key Vault

from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
from carbonarc import CarbonArcClient

def get_client_azure(vault_url):
"""Load token from Azure Key Vault."""
credential = DefaultAzureCredential()
client = SecretClient(vault_url=vault_url, credential=credential)
token = client.get_secret("carbonarc-token").value
return CarbonArcClient(host="https://api.carbonarc.co", token=token)

Testing Your Connection

from carbonarc import CarbonArcClient
import os

def test_connection(host, token):
"""Test if authentication credentials are valid."""
try:
client = CarbonArcClient(host=host, token=token)
result = client.data.get_datasets()

print("Connection successful!")
print(f" Host: {host}")
print(f" Token: {token[:8]}...{token[-4:]}") # Mask middle
return client

except Exception as e:
print(f"Connection failed!")
print(f" Error: {e}")
return None

# Usage
client = test_connection(
host="https://api.carbonarc.co",
token=os.environ.get("CARBONARC_TOKEN")
)

Security Best Practices

Do

  • Store tokens in environment variables or secrets managers
  • Rotate tokens periodically
  • Use .env files for local development (with .gitignore)
  • Mask tokens in logs: token[:8] + "..." + token[-4:]

Don't

  • Hardcode tokens in source code
  • Commit .env files to version control
  • Share tokens via email or chat
  • Log full tokens in application logs

.gitignore Template

# Environment files
.env
.env.local
.env.*.local

# Config files with secrets
config.local.yaml
*secrets*

Quick Reference

Client Initialization

from carbonarc import CarbonArcClient
import os

client = CarbonArcClient(
host=os.environ.get("CARBONARC_HOST", "https://api.carbonarc.co"),
token=os.environ["CARBONARC_TOKEN"]
)

Environment Variables

VariableRequiredDescription
CARBONARC_TOKENYesYour API token
CARBONARC_HOSTNoAPI endpoint (defaults to production)

Method Comparison

MethodSecurityUse Case
DirectLowQuick tests only
Environment VarsGoodCI/CD, containers, scripts
.env FileGoodLocal development
Config + EnvGoodComplex projects, multiple settings
Secrets ManagerBestProduction cloud deployments

Next Steps