Перейти к основному содержанию
GET
/
v1
/
user
/
balance
curl --request GET \
  --url 'https://api.apimart.ai/v1/user/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_user_balance():
    response = requests.get(f'{API_BASE}/v1/user/balance', headers=headers)
    data = response.json()
    
    if data.get('success'):
        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_user_balance()
const API_BASE = 'https://api.apimart.ai';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

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

getUserBalance();
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"`
}

func main() {
    url := "https://api.apimart.ai/v1/user/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 {
        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/user/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/user/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']) {
    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/user/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']
  puts "Remaining balance: #{data['remain_balance']}"
  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/user/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/user/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": 100.0,
  "remain_credits": 1000,
  "used_balance": 25.5,
  "used_credits": 255
}
{
  "success": false,
  "message": "Failed to get user quota: record not found"
}
{
  "success": false,
  "message": "Failed to get used quota: 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"
  }
}
Получите оставшийся и использованный баланс текущего пользовательского аккаунта. Этот эндпоинт возвращает информацию о балансе на уровне пользователя, независимо от конкретных токенов, и предназначен для просмотра общего баланса аккаунта.
curl --request GET \
  --url 'https://api.apimart.ai/v1/user/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_user_balance():
    response = requests.get(f'{API_BASE}/v1/user/balance', headers=headers)
    data = response.json()
    
    if data.get('success'):
        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_user_balance()
const API_BASE = 'https://api.apimart.ai';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

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

getUserBalance();
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"`
}

func main() {
    url := "https://api.apimart.ai/v1/user/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 {
        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/user/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/user/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']) {
    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/user/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']
  puts "Remaining balance: #{data['remain_balance']}"
  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/user/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/user/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": 100.0,
  "remain_credits": 1000,
  "used_balance": 25.5,
  "used_credits": 255
}
{
  "success": false,
  "message": "Failed to get user quota: record not found"
}
{
  "success": false,
  "message": "Failed to get used quota: 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/user/balance
GET /user/balance
Оба эндпоинта обладают одинаковой функциональностью — вы можете использовать любой из них.

Ответ

success
boolean
Успешно ли выполнен запрос
message
string
Сообщение об ошибке (возвращается только при ошибке)
remain_balance
float
Оставшийся баланс пользователя (возвращается при успешном выполнении).
remain_credits
integer
Оставшиеся кредиты пользователя (возвращается при успешном выполнении).
used_balance
float
Использованный баланс пользователя (возвращается при успешном выполнении)
used_credits
float
Использованные кредиты пользователя (возвращается при успешном выполнении)

Баланс токена и баланс пользователя

СравнениеБаланс токена (/v1/balance)Баланс пользователя (/v1/user/balance)
ОбластьОдин токенВесь пользовательский аккаунт
Источник данныхRemainQuota и UsedQuota токенаquota и used_quota пользователя
СценарийМониторинг использования одного API-ключаПросмотр общего баланса аккаунта
ОграничениеЛимитами на уровне токенаЛимитами на уровне пользователя

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

  • Просмотр общего баланса пользовательского аккаунта
  • Настройка напоминаний о пополнении и оповещений о балансе
  • Отображение баланса аккаунта в личном кабинете пользователя
Информация о единицах балансаЕдиница значения баланса зависит от конфигурации системы:
  • USD — доллары США
  • CNY — китайские юани
  • Tokens — количество токенов

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

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