> ## Documentation Index
> Fetch the complete documentation index at: https://polza.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# GET Key

> Лимит и расход API-ключа, которым сделан запрос

Возвращает лимит и расход того API-ключа, с которым пришёл запрос. Работает только с API-ключом: с токеном личного кабинета вернётся `400`. Баланс организации здесь не показывается — для него есть [`GET /v2/balance`](/docs/api-reference/other/balance-v2).

## Примеры

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://polza.ai/api/v1/key" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://polza.ai/api/v1/key',
      headers={'Authorization': 'Bearer YOUR_API_KEY'}
  )

  key = response.json()
  print(f"Потрачено за месяц: {key['usage_monthly']} руб., осталось: {key['limit_remaining']}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://polza.ai/api/v1/key', {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });

  const key = await response.json();
  console.log(`Потрачено за месяц: ${key.usage_monthly} руб., осталось: ${key.limit_remaining}`);
  ```
</CodeGroup>

## Ответ

```json theme={null}
{
  "creator_user_id": "usr_1234567890123456789",
  "label": "pza_AbCd••••••••••••••••••••XyZ123",
  "limit": 5000,
  "limit_remaining": 3820.5,
  "limit_reset": "monthly",
  "usage": 12450.75,
  "usage_daily": 96.1,
  "usage_weekly": 410.2,
  "usage_monthly": 1179.5
}
```

Все суммы — в рублях.

| Поле | Описание |
| - | - |
| `creator_user_id` | Пользователь, создавший ключ |
| `label` | Маска ключа (не имя ключа) |
| `limit` | Лимит расходов ключа; `null` — лимит не задан |
| `limit_remaining` | Сколько осталось до лимита в текущем периоде; `null` — лимит не задан |
| `limit_reset` | Период лимита: `daily`, `weekly`, `monthly` или `never` (лимит на всё время); `null` — лимит не задан |
| `usage` | Расход по ключу за всё время |
| `usage_daily` | Расход за текущий день |
| `usage_weekly` | Расход за текущую неделю (с понедельника) |
| `usage_monthly` | Расход за текущий месяц (с 1-го числа) |

Периоды начинаются в 01:00 по московскому времени. Когда лимит исчерпан, запросы с этим ключом получают `402`.

<Note>
  Имена полей совместимы с `GET /api/v1/key` OpenRouter, но ответ приходит без обёртки `data`, а суммы указаны в рублях.
</Note>


## OpenAPI

````yaml GET /v1/key
openapi: 3.0.0
info:
  title: Polza.ai API
  description: AI агрегатор — унифицированный доступ к сотням AI моделей
  version: '1.0'
  contact: {}
servers:
  - url: https://polza.ai/api
    description: Production
security: []
tags: []
paths:
  /v1/key:
    get:
      tags:
        - Публичный API
      summary: Информация о текущем API-ключе
      description: >-
        Возвращает данные о ключе, по которому был сделан запрос: создателя,
        маску, лимиты и использование.
      operationId: PublicKeyController_getKey[1]
      parameters: []
      responses:
        '200':
          description: ''
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PublicKeyPresenter'
        '400':
          description: Некорректный запрос. Проверьте параметры и тело
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '401':
          description: Ошибка авторизации. Проверьте ключ доступа
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '402':
          description: Недостаточно средств или достигнут лимит
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '403':
          description: Ошибка доступа. Проверьте права доступа ключа
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '404':
          description: Ресурс не найден
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '408':
          description: Истекло время ожидания ответа. Повторите запрос
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '409':
          description: Конфликт состояния. Перечитайте ресурс и повторите запрос
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '413':
          description: Размер тела запроса превышает допустимый предел
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '429':
          description: Слишком много запросов. Повторите позже
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '500':
          description: Ошибка сервера. Обратитесь к поставщику услуг
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '502':
          description: Поставщик услуг вернул некорректный ответ
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
        '503':
          description: Сервис временно недоступен. Повторите позже
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiErrorPresenter'
      security:
        - bearer: []
components:
  schemas:
    PublicKeyPresenter:
      type: object
      properties:
        creator_user_id:
          type: object
          description: ID пользователя, создавшего ключ
          example: usr_2101001970415296513
          nullable: true
        label:
          type: string
          example: pza_abc1••••••••••••••••••••xyz789
          description: Маскированный ключ для отображения
        limit:
          type: object
          description: Лимит ключа в рублях; null — лимит не задан
          example: 100
          nullable: true
        limit_remaining:
          type: object
          description: Остаток лимита в рублях; null — лимит не задан
          example: 74.5
          nullable: true
        limit_reset:
          type: string
          description: Период сброса лимита; null — лимит не задан
          example: monthly
          enum:
            - daily
            - weekly
            - monthly
            - never
          nullable: true
        usage:
          type: number
          description: Всего потрачено по ключу за всё время в рублях
          example: 25.5
        usage_daily:
          type: number
          description: Потрачено за текущий день в рублях
          example: 25.5
        usage_weekly:
          type: number
          description: Потрачено за текущую неделю в рублях
          example: 25.5
        usage_monthly:
          type: number
          description: Потрачено за текущий месяц в рублях
          example: 25.5
      required:
        - creator_user_id
        - label
        - limit
        - limit_remaining
        - limit_reset
        - usage
        - usage_daily
        - usage_weekly
        - usage_monthly
    ApiErrorPresenter:
      type: object
      properties:
        error:
          description: Информация об ошибке
          allOf:
            - $ref: '#/components/schemas/ApiErrorBodyPresenter'
        trace_id:
          type: string
          description: ID трассировки запроса
          example: 550e8400-e29b-41d4-a716-446655440000
      required:
        - error
    ApiErrorBodyPresenter:
      type: object
      properties:
        code:
          type: string
          description: Код ошибки
          enum:
            - BAD_REQUEST
            - UNAUTHORIZED
            - api_key_revoked
            - INSUFFICIENT_BALANCE
            - FORBIDDEN
            - NOT_FOUND
            - REQUEST_TIMEOUT
            - CONFLICT
            - PAYLOAD_TOO_LARGE
            - TOO_MANY_REQUESTS
            - BAD_GATEWAY
            - SERVICE_UNAVAILABLE
            - INTERNAL_ERROR
          example: BAD_REQUEST
        message:
          type: string
          description: Описание ошибки
          example: Недопустимое значение параметра
        trace_id:
          type: string
          description: ID трассировки запроса
          example: 550e8400-e29b-41d4-a716-446655440000
        details:
          type: object
          description: Уточняющие поля ошибки. Отдаются только для 4xx
          additionalProperties: true
        metadata:
          description: Метаданные ошибки провайдера
          allOf:
            - $ref: '#/components/schemas/ApiErrorMetadataPresenter'
      required:
        - code
        - message
    ApiErrorMetadataPresenter:
      type: object
      properties:
        reason:
          type: string
          description: 'Машинная причина отказа: по ней можно ветвиться, не разбирая текст'
          example: noProvidersForModel
        raw:
          type: string
          description: Исходный текст ответа провайдера
          example: The parameter `duration` specified in the request is not valid
        provider_name:
          type: string
          description: Провайдер, вернувший ошибку
          example: alibaba
  securitySchemes:
    bearer:
      scheme: bearer
      bearerFormat: API Key
      type: http
      description: >-
        API ключ передаётся в заголовке: Authorization: Bearer
        <POLZA_AI_API_KEY>

````