CodexBar API: How to Programmatically Access Usage Data via Swift and CLI

Yes, CodexBar exposes two primary programmable interfaces: a Swift-level core library for embedding in macOS applications and a command-line binary for automation scripts and CI pipelines.

CodexBar, developed by steipete/CodexBar as an open-source macOS menu-bar application, provides a clean CodexBar API surface that allows developers to fetch AI provider usage data without launching the GUI. Whether you are building a custom dashboard or automating cost monitoring, you can integrate directly with the CodexBarCore Swift package or invoke the bundled codexbar CLI tool to retrieve quota metrics from OpenAI, Codex, and other supported providers.

Swift-Level CodexBar API

The core library (CodexBarCore) powers the macOS application and defines a provider-agnostic model for configuring token resolution and executing fetch pipelines. Because the entire stack is pure Swift, any Swift project can import the package and call the public API to obtain usage data.

ProviderDescriptor and Fetch Pipelines

The entry point for any provider is the ProviderDescriptor enum, defined in Sources/CodexBarCore/Providers/ProviderDescriptor.swift. This enum maps each provider ID (e.g., .openai, .codex) to a descriptor that contains the logic for resolving credentials and determining which fetch strategies to execute.

Each descriptor encapsulates a fetch pipeline composed of concrete ProviderFetchStrategy implementations. For example:

These strategies invoke low-level fetchers that communicate directly with provider admin APIs or OAuth endpoints.

UsageSnapshot Results

The result of a completed pipeline is a UsageSnapshot (defined in Sources/CodexBarCore/UsageFetcher.swift) containing per-provider metrics such as quota limits, current spend, and reset times. This snapshot is ready for UI rendering or further programmatic processing.

import CodexBarCore

// Resolve the OpenAI provider descriptor
let descriptor = ProviderDescriptor.openai

// Build a fetch pipeline (the descriptor already contains the pipeline)
let fetcher = descriptor.pipeline

// Run the pipeline for the current environment (process env vars, config file, etc.)
let usage = try await fetcher.fetch(
    context: ProviderFetchContext(
        env: ProcessInfo.processInfo.environment,
        config: try CodexBarConfig.load()
    )
)

// `usage.openAIAPIUsage` now contains the decoded OpenAI snapshot
print("Current spend (USD):", usage.openAIAPIUsage?.totalSpendUSD ?? "n/a")

Command-Line CodexBar API

For headless environments, CI pipelines, or shell scripting, CodexBar bundles a binary named codexbar. The CLI reads the same configuration file (~/.config/codexbar/config.json) used by the GUI and exposes commands for authentication, provider management, and usage reporting.

Configuration and Authentication

The CLI can bootstrap API keys and enable providers without user interaction. According to the documentation in docs/cli-configuration.md, you can programmatically set keys and toggle providers:


# Store an OpenAI admin key without opening the GUI

printf '%s' "$OPENAI_API_KEY" | codexbar config set-api-key --provider openai --stdin

# Enable a provider (e.g., Claude)

codexbar config enable --provider claude

Internally, the CLI entry point in Sources/CodexBar/CodexbarApp.swift parses these arguments, builds a CodexBarConfig instance, and dispatches to the same shared UsageFetcher logic used by the Swift library.

Automated Usage Reporting

The usage command outputs concise summaries for all enabled providers. When invoked with --format json, it returns structured data suitable for parsing by jq or other tools:

#!/usr/bin/env bash

# Refresh every 5 minutes and alert when a quota exceeds 90%

while true; do
  # Grab the JSON usage payload

  payload=$(codexbar usage --format json)

  # Extract the OpenAI usage percentage (jq must be installed)

  pct=$(echo "$payload" | jq -r '.openAIAPIUsage?.percentageUsed // 0')

  if (( $(echo "$pct > 90" | bc -l) )); then
    echo "⚠️ OpenAI quota >90% (currently $pct%)"
  fi
  sleep 300
done

Summary

  • CodexBar exposes a dual API: Import CodexBarCore as a Swift Package Manager dependency for native integration, or run the codexbar binary for shell-based automation.
  • Provider abstraction: The ProviderDescriptor enum and ProviderFetchStrategy protocol create a uniform interface across different AI services, with concrete implementations like OpenAIAPIUsageFetcher handling provider-specific protocols.
  • Shared configuration: Both the Swift library and CLI read from ~/.config/codexbar/config.json and use CodexBarConfig.swift for validation, ensuring consistent behavior between GUI and scripted environments.
  • Pure Swift architecture: The core fetch stack contains no UI dependencies, allowing it to compile for macOS app extensions or Linux command-line builds.

Frequently Asked Questions

Can I use the CodexBar API without running the macOS menu-bar app?

Yes. The codexbar CLI binary is designed for headless operation and can be built for Linux or macOS. It uses the same configuration file and core logic as the GUI but requires no Cocoa dependencies, making it suitable for servers and CI environments.

Where does the CodexBar API store configuration and API keys?

Configuration is stored in ~/.config/codexbar/config.json. Both the Swift library (via CodexBarConfig.load() in Sources/CodexBarCore/Config/CodexBarConfig.swift) and the CLI read from this location. The file stores encrypted API keys and provider enablement flags, ensuring consistency across programmatic interfaces.

Is the CodexBar Swift API available on Linux?

The core library (CodexBarCore) is pure Swift and can target Linux, but the menu-bar application (CodexBar) requires macOS. To use the API on Linux, import only the CodexBarCore target in your Package.swift and avoid UI-dependent modules. The CLI binary is also compatible with Linux builds.

How do I add support for a new AI provider via the CodexBar API?

Extend the ProviderDescriptor enum and implement ProviderFetchStrategy. You must create a new descriptor in Sources/CodexBarCore/Providers/ that defines how to resolve credentials and instantiate your custom fetcher. The fetcher should return a UsageSnapshot conforming to the schema defined in Sources/CodexBarCore/UsageFetcher.swift, allowing seamless integration with existing CLI and library consumers.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →