Code Examples

Ready-to-use examples for common integration scenarios.

C# Examples

Reusable Client with API Key Auth

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class BassodeClient
{
    private readonly HttpClient _httpClient;
    private const string BaseUrl = "https://api.bassode.com";

    public BassodeClient(string apiKey, string apiSecret)
    {
        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
        _httpClient.DefaultRequestHeaders.Add("X-Api-Secret", apiSecret);
    }

    // Set JWT after login — required for user-specific endpoints
    public void SetJwt(string token)
    {
        _httpClient.DefaultRequestHeaders.Remove("Authorization");
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
    }

    public async Task<string> GetDacCatalogAsync()
    {
        var response = await _httpClient.GetAsync($"{BaseUrl}/api/Dac");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    public async Task<LoginResponse> LoginAsync(string email, string password)
    {
        var body = JsonSerializer.Serialize(new { email, password });
        var content = new StringContent(body, Encoding.UTF8, "application/json");
        var response = await _httpClient.PostAsync($"{BaseUrl}/api/Users/Login", content);
        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<LoginResponse>(json,
            new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
    }
}

public class LoginResponse
{
    public string Token { get; set; }
    public DateTime ExpiresAt { get; set; }
    public UserInfo User { get; set; }
}

public class UserInfo
{
    public int Id { get; set; }
    public string Email { get; set; }
    public int Role { get; set; }
    public bool IsTrialSubscription { get; set; }
}

// Usage
var client = new BassodeClient(
    Environment.GetEnvironmentVariable("BASSODE_API_KEY"),
    Environment.GetEnvironmentVariable("BASSODE_API_SECRET")
);

// Query catalog without login
var catalog = await client.GetDacCatalogAsync();

// Login a user and access subscriber endpoints
var loginResult = await client.LoginAsync("user@example.com", "password");
client.SetJwt(loginResult.Token);
// Now you can call /api/ApiKeys, /api/Devices, etc.

Login and List API Keys

var client = new BassodeClient(apiKey, apiSecret);

// Login
var login = await client.LoginAsync("user@example.com", "password");
client.SetJwt(login.Token);

// Check subscription status
if (login.User.Role < 1)
{
    Console.WriteLine("User does not have an active subscription.");
    return;
}

// Fetch API keys
var response = await client.GetAsync("https://api.bassode.com/api/ApiKeys");
var json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);

JavaScript Examples

Fetch API — Query the Catalog

const API_KEY = process.env.BASSODE_API_KEY;
const API_SECRET = process.env.BASSODE_API_SECRET;
const BASE_URL = 'https://api.bassode.com';

async function getDacCatalog(params = {}) {
  const query = new URLSearchParams(params).toString();
  const url = `${BASE_URL}/api/Dac${query ? '?' + query : ''}`;

  const response = await fetch(url, {
    headers: {
      'X-Api-Key': API_KEY,
      'X-Api-Secret': API_SECRET
    }
  });

  if (!response.ok) {
    const err = await response.json();
    throw new Error(`${response.status}: ${err.message}`);
  }

  return response.json();
}

// Usage
const catalog = await getDacCatalog({ brand: 'Chord', page: 1 });
console.log(catalog);

Login and Manage API Keys

const BASE_URL = 'https://api.bassode.com';

async function login(email, password) {
  const response = await fetch(`${BASE_URL}/api/Users/Login`, {
    method: 'POST',
    headers: {
      'X-Api-Key': process.env.BASSODE_API_KEY,
      'X-Api-Secret': process.env.BASSODE_API_SECRET,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ email, password })
  });

  if (!response.ok) throw new Error('Login failed');
  return response.json();
}

async function listApiKeys(jwt) {
  const response = await fetch(`${BASE_URL}/api/ApiKeys`, {
    headers: {
      'X-Api-Key': process.env.BASSODE_API_KEY,
      'X-Api-Secret': process.env.BASSODE_API_SECRET,
      'Authorization': `Bearer ${jwt}`
    }
  });

  if (response.status === 403) {
    console.error('User does not have an active subscription.');
    return [];
  }

  return response.json();
}

// Usage
const { token, user } = await login('user@example.com', 'password');
console.log(`Logged in as ${user.email}, role: ${user.role}`);

const keys = await listApiKeys(token);
console.log('API Keys:', keys);

Python Examples

Query the Catalog

import os
import requests

BASE_URL = 'https://api.bassode.com'
HEADERS = {
    'X-Api-Key': os.environ['BASSODE_API_KEY'],
    'X-Api-Secret': os.environ['BASSODE_API_SECRET']
}

def get_dac_catalog(brand=None, page=1, page_size=50):
    params = {'page': page, 'pageSize': page_size}
    if brand:
        params['brand'] = brand
    response = requests.get(f'{BASE_URL}/api/Dac', headers=HEADERS, params=params)
    response.raise_for_status()
    return response.json()

# Usage
catalog = get_dac_catalog(brand='Chord')
print(catalog)

Login and Create an API Key

import os
import requests

BASE_URL = 'https://api.bassode.com'
API_HEADERS = {
    'X-Api-Key': os.environ['BASSODE_API_KEY'],
    'X-Api-Secret': os.environ['BASSODE_API_SECRET']
}

def login(email, password):
    response = requests.post(
        f'{BASE_URL}/api/Users/Login',
        headers={**API_HEADERS, 'Content-Type': 'application/json'},
        json={'email': email, 'password': password}
    )
    response.raise_for_status()
    return response.json()

def create_api_key(jwt, name, scopes):
    headers = {**API_HEADERS, 'Authorization': f'Bearer {jwt}',
               'Content-Type': 'application/json'}
    response = requests.post(
        f'{BASE_URL}/api/ApiKeys',
        headers=headers,
        json={'name': name, 'scopes': scopes}
    )
    if response.status_code == 403:
        raise Exception('User does not have an active subscription')
    response.raise_for_status()
    return response.json()

# Usage
login_result = login('user@example.com', 'password')
jwt = login_result['token']

new_key = create_api_key(jwt, 'My App Key', 'auth:login read:devices')
print(f"Key: {new_key['key']}")
print(f"Secret: {new_key['secret']}")  # Save this — shown only once

cURL Examples

Query the DAC Catalog

curl https://api.bassode.com/api/Dac \
  -H "X-Api-Key: bsk_live_xxxxxxxxxxxxxx" \
  -H "X-Api-Secret: your_secret_here"

Login

curl -X POST https://api.bassode.com/api/Users/Login \
  -H "X-Api-Key: bsk_live_xxxxxxxxxxxxxx" \
  -H "X-Api-Secret: your_secret_here" \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"yourpassword"}'

List API Keys (with JWT)

curl https://api.bassode.com/api/ApiKeys \
  -H "X-Api-Key: bsk_live_xxxxxxxxxxxxxx" \
  -H "X-Api-Secret: your_secret_here" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Register a User

curl -X POST https://api.bassode.com/api/Users/Register \
  -H "X-Api-Key: bsk_live_xxxxxxxxxxxxxx" \
  -H "X-Api-Secret: your_secret_here" \
  -H "Content-Type: application/json" \
  -d '{"email":"newuser@example.com","password":"SecurePassword1!","firstName":"Jane","lastName":"Doe"}'

Next Steps