Перейти к основному содержанию
GET
/
v1
/
balance
curl --request GET \
  --url 'https://api.apimart.ai/v1/balance' \
  --header 'Authorization: Bearer <token>'
import requests

API_BASE = 'https://api.apimart.ai'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'

headers = {
    'Authorization': f'Bearer {API_KEY}'
}

def get_token_balance():
    response = requests.get(f'{API_BASE}/v1/balance', headers=headers)
    data = response.json()
    
    if data.get('success'):
        if data.get('unlimited_quota'):
            print("Quota: Unlimited")
        else:
            print(f"Remaining balance: {data['remain_balance']}")
        print(f"Used balance: {data['used_balance']}")
    else:
        print(f"Query failed: {data.get('message')}")
    
    return data

get_token_balance()
const API_BASE = 'https://api.apimart.ai';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

async function getTokenBalance() {
  const response = await fetch(`${API_BASE}/v1/balance`, {
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    }
  });
  
  const data = await response.json();
  
  if (data.success) {
    if (data.unlimited_quota) {
      console.log('Quota: Unlimited');
    } else {
      console.log(`Remaining balance: ${data.remain_balance}`);
    }
    console.log(`Used balance: ${data.used_balance}`);
  } else {
    console.error('Query failed:', data.message);
  }
  
  return data;
}

getTokenBalance();
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type BalanceResponse struct {
    Success        bool    `json:"success"`
    Message        string  `json:"message,omitempty"`
    RemainBalance  float64 `json:"remain_balance"`
    UsedBalance    float64 `json:"used_balance"`
    UnlimitedQuota bool    `json:"unlimited_quota"`
}

func main() {
    url := "https://api.apimart.ai/v1/balance"

    req, _ := http.NewRequest("GET", url, nil)
    req.Header.Set("Authorization", "Bearer <token>")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    
    var result BalanceResponse
    json.Unmarshal(body, &result)
    
    if result.Success {
        if result.UnlimitedQuota {
            fmt.Println("Quota: Unlimited")
        } else {
            fmt.Printf("Remaining balance: %.2f\n", result.RemainBalance)
        }
        fmt.Printf("Used balance: %.2f\n", result.UsedBalance)
    }
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class Main {
    public static void main(String[] args) throws Exception {
        String url = "https://api.apimart.ai/v1/balance";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", "Bearer <token>")
            .GET()
            .build();

        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
<?php

$api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

$ch = curl_init('https://api.apimart.ai/v1/balance');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $api_key"
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

if ($data['success']) {
    if ($data['unlimited_quota']) {
        echo "Quota: Unlimited\n";
    } else {
        echo "Remaining balance: " . $data['remain_balance'] . "\n";
    }
    echo "Used balance: " . $data['used_balance'] . "\n";
} else {
    echo "Query failed: " . $data['message'] . "\n";
}
?>
require 'net/http'
require 'json'
require 'uri'

api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxx'

url = URI("https://api.apimart.ai/v1/balance")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Get.new(url)
request["Authorization"] = "Bearer #{api_key}"

response = http.request(request)
data = JSON.parse(response.body)

if data['success']
  if data['unlimited_quota']
    puts "Quota: Unlimited"
  else
    puts "Remaining balance: #{data['remain_balance']}"
  end
  puts "Used balance: #{data['used_balance']}"
else
  puts "Query failed: #{data['message']}"
end
import Foundation

let apiKey = "sk-xxxxxxxxxxxxxxxxxxxxxx"
let url = URL(string: "https://api.apimart.ai/v1/balance")!

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    
    if let data = data, let responseString = String(data: data, encoding: .utf8) {
        print(responseString)
    }
}

task.resume()
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var apiKey = "sk-xxxxxxxxxxxxxxxxxxxxxx";
        var url = "https://api.apimart.ai/v1/balance";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

        var response = await client.GetAsync(url);
        var result = await response.Content.ReadAsStringAsync();

        Console.WriteLine(result);
    }
}
{
  "success": true,
  "remain_balance": 10.5,
  "remain_credits": 105,
  "used_balance": 2.3,
  "used_credits": 23,
  "unlimited_quota": false
}
{
  "success": true,
  "remain_balance": -1,
  "remain_credits": -1,
  "used_balance": 2.3,
  "used_credits": 23,
  "unlimited_quota": true
}
{
  "success": false,
  "message": "Failed to get token info: record not found"
}
{
  "error": {
    "code": 401,
    "message": "Invalid authentication credentials",
    "type": "authentication_error"
  }
}
{
  "error": {
    "code": 429,
    "message": "Rate limit exceeded. Please try again later",
    "type": "rate_limit_error"
  }
}
Получите оставшийся и использованный баланс текущего API-ключа (токена). Этот эндпоинт используется для мониторинга использования отдельного токена.
curl --request GET \
  --url 'https://api.apimart.ai/v1/balance' \
  --header 'Authorization: Bearer <token>'
import requests

API_BASE = 'https://api.apimart.ai'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'

headers = {
    'Authorization': f'Bearer {API_KEY}'
}

def get_token_balance():
    response = requests.get(f'{API_BASE}/v1/balance', headers=headers)
    data = response.json()
    
    if data.get('success'):
        if data.get('unlimited_quota'):
            print("Quota: Unlimited")
        else:
            print(f"Remaining balance: {data['remain_balance']}")
        print(f"Used balance: {data['used_balance']}")
    else:
        print(f"Query failed: {data.get('message')}")
    
    return data

get_token_balance()
const API_BASE = 'https://api.apimart.ai';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

async function getTokenBalance() {
  const response = await fetch(`${API_BASE}/v1/balance`, {
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    }
  });
  
  const data = await response.json();
  
  if (data.success) {
    if (data.unlimited_quota) {
      console.log('Quota: Unlimited');
    } else {
      console.log(`Remaining balance: ${data.remain_balance}`);
    }
    console.log(`Used balance: ${data.used_balance}`);
  } else {
    console.error('Query failed:', data.message);
  }
  
  return data;
}

getTokenBalance();
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type BalanceResponse struct {
    Success        bool    `json:"success"`
    Message        string  `json:"message,omitempty"`
    RemainBalance  float64 `json:"remain_balance"`
    UsedBalance    float64 `json:"used_balance"`
    UnlimitedQuota bool    `json:"unlimited_quota"`
}

func main() {
    url := "https://api.apimart.ai/v1/balance"

    req, _ := http.NewRequest("GET", url, nil)
    req.Header.Set("Authorization", "Bearer <token>")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    
    var result BalanceResponse
    json.Unmarshal(body, &result)
    
    if result.Success {
        if result.UnlimitedQuota {
            fmt.Println("Quota: Unlimited")
        } else {
            fmt.Printf("Remaining balance: %.2f\n", result.RemainBalance)
        }
        fmt.Printf("Used balance: %.2f\n", result.UsedBalance)
    }
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class Main {
    public static void main(String[] args) throws Exception {
        String url = "https://api.apimart.ai/v1/balance";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", "Bearer <token>")
            .GET()
            .build();

        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
<?php

$api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

$ch = curl_init('https://api.apimart.ai/v1/balance');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $api_key"
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

if ($data['success']) {
    if ($data['unlimited_quota']) {
        echo "Quota: Unlimited\n";
    } else {
        echo "Remaining balance: " . $data['remain_balance'] . "\n";
    }
    echo "Used balance: " . $data['used_balance'] . "\n";
} else {
    echo "Query failed: " . $data['message'] . "\n";
}
?>
require 'net/http'
require 'json'
require 'uri'

api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxx'

url = URI("https://api.apimart.ai/v1/balance")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Get.new(url)
request["Authorization"] = "Bearer #{api_key}"

response = http.request(request)
data = JSON.parse(response.body)

if data['success']
  if data['unlimited_quota']
    puts "Quota: Unlimited"
  else
    puts "Remaining balance: #{data['remain_balance']}"
  end
  puts "Used balance: #{data['used_balance']}"
else
  puts "Query failed: #{data['message']}"
end
import Foundation

let apiKey = "sk-xxxxxxxxxxxxxxxxxxxxxx"
let url = URL(string: "https://api.apimart.ai/v1/balance")!

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    
    if let data = data, let responseString = String(data: data, encoding: .utf8) {
        print(responseString)
    }
}

task.resume()
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var apiKey = "sk-xxxxxxxxxxxxxxxxxxxxxx";
        var url = "https://api.apimart.ai/v1/balance";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

        var response = await client.GetAsync(url);
        var result = await response.Content.ReadAsStringAsync();

        Console.WriteLine(result);
    }
}
{
  "success": true,
  "remain_balance": 10.5,
  "remain_credits": 105,
  "used_balance": 2.3,
  "used_credits": 23,
  "unlimited_quota": false
}
{
  "success": true,
  "remain_balance": -1,
  "remain_credits": -1,
  "used_balance": 2.3,
  "used_credits": 23,
  "unlimited_quota": true
}
{
  "success": false,
  "message": "Failed to get token info: record not found"
}
{
  "error": {
    "code": 401,
    "message": "Invalid authentication credentials",
    "type": "authentication_error"
  }
}
{
  "error": {
    "code": 429,
    "message": "Rate limit exceeded. Please try again later",
    "type": "rate_limit_error"
  }
}

Авторизация

Authorization
string
обязательно
Все API-эндпоинты требуют аутентификации с помощью Bearer TokenПолучите свой API-ключ:Перейдите на страницу управления API-ключами, чтобы получить API-ключДобавьте его в заголовок запроса:
Authorization: Bearer YOUR_API_KEY

Эндпоинты

GET /v1/balance
GET /balance
Оба эндпоинта обладают одинаковой функциональностью — вы можете использовать любой из них.

Ответ

success
boolean
Успешно ли выполнен запрос
message
string
Сообщение об ошибке (возвращается только при ошибке)
remain_balance
float
Оставшийся баланс токена (возвращается при успешном выполнении). Возвращает -1, когда unlimited_quota равно true
remain_credits
integer
Оставшиеся кредиты токена (возвращается при успешном выполнении). Возвращает -1, когда unlimited_quota равно true
used_balance
float
Использованный баланс токена (возвращается при успешном выполнении)
used_credits
integer
Использованные кредиты токена (возвращается при успешном выполнении)
unlimited_quota
boolean
Является ли квота токена безлимитной. true — безлимитная, false — ограниченная

Сценарии использования

  • Мониторинг расхода отдельного API-ключа
  • Отображение текущего баланса токена в вашем приложении
  • Настройка оповещений при падении баланса ниже порогового значения
Информация о единицах балансаЕдиница значения баланса зависит от конфигурации системы:
  • USD — доллары США
  • Credits — Кредиты
Токен с безлимитной квотойКогда для токена установлена безлимитная квота:
  • поле unlimited_quota возвращает true
  • поле remain_balance возвращает -1
  • поле remain_credits возвращает -1
  • токен не имеет ограничений по квоте и может использоваться без лимитов

Частые ошибки

Сообщение об ошибкеПричинаРешение
No Authorization headerЗаголовок Authorization не указанДобавьте заголовок Authorization: Bearer sk-xxxxx
Failed to get token infoТокен не существует или был удалёнПроверьте корректность ключа токена
Замечание по безопасностиВаш API-ключ — как пароль. Храните его в безопасности и не передавайте другим. В рабочей среде всегда используйте HTTPS.