Skip to main content
Retrieve your current API credit balance from the /v1/account/credits endpoint. This endpoint provides detailed information about all credit types associated with your account, including regular credits, free credits, referral credits, and the total available balance.
Credits are automatically deducted after each API request completes. Free credits are used first, followed by regular credits. Check your balance regularly to ensure you have sufficient credits for your operations.

Quick Start

import os
import json
import requests
from dotenv import load_dotenv

load_dotenv()

API_KEY = os.getenv("SWARMS_API_KEY")
BASE_URL = "https://api.swarms.world"

headers = {
    "x-api-key": API_KEY,
    "Content-Type": "application/json",
}

def get_credit_balance() -> dict | None:
    """Fetch current credit balance for the authenticated user."""
    resp = requests.get(f"{BASE_URL}/v1/account/credits", headers=headers)

    if resp.status_code == 200:
        return resp.json()

    print(f"Error: {resp.status_code} - {resp.text}")
    return None

if __name__ == "__main__":
    data = get_credit_balance()
    if data:
        print("✅ Credit balance retrieved successfully!")
        print(f"Total Credits: ${data.get('total_credits', 0):.2f}")
        print(f"Regular Credits: ${data.get('credit', 0):.2f}")
        print(f"Free Credits: ${data.get('free_credit', 0):.2f}")
        print(f"Referral Credits: ${data.get('referral_credits', 0):.2f}")
        print(json.dumps(data, indent=2))

Response Schema

CreditBalanceOutput Object

FieldTypeDescription
creditnumberRegular credit balance (purchased credits)
free_creditnumberFree credit balance (promotional or welcome credits)
referral_creditsnumberCredits earned through the referral program
total_creditsnumberTotal available credits (sum of all credit types)

Example Response

{
  "credit": 50.00,
  "free_credit": 20.00,
  "referral_credits": 5.00,
  "total_credits": 75.00
}

Credit Usage Order

Credits are deducted in the following order:
  1. Free Credits - Used first for all API operations
  2. Referral Credits - Used after free credits are exhausted
  3. Regular Credits - Used last (purchased credits)
This ensures you maximize the value of promotional and earned credits before using purchased credits.

Use Cases

Monitor Credit Balance

Check your credit balance before running large batch operations:
def check_balance_before_batch():
    balance = get_credit_balance()
    if balance and balance['total_credits'] < 10.00:
        print("⚠️ Low credit balance. Consider adding credits before running batch operations.")
        return False
    return True

if check_balance_before_batch():
    # Run batch operations
    pass

Track Credit Consumption

Monitor credit usage over time:
import time
from datetime import datetime

def track_credits(duration_minutes=60, interval_seconds=300):
    """Track credit balance over time."""
    end_time = time.time() + (duration_minutes * 60)
    
    while time.time() < end_time:
        balance = get_credit_balance()
        if balance:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"[{timestamp}] Total Credits: ${balance['total_credits']:.2f}")
        
        time.sleep(interval_seconds)

Best Practices

  1. Regular Monitoring: Check your credit balance regularly, especially before large operations
  2. Low Balance Alerts: Set up alerts when credits fall below a threshold
  3. Credit Types: Understand which credit types you’re using to optimize spending
  4. Referral Program: Earn additional credits by referring new users