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

# API 토큰 생성

> Create a new API token via API

> [!NOTE]
>
> **중국 본토 사용자 안내:** 중국 본토 사용자는 `https://toapis.cn` 를 API 엔드포인트(Base URL)로 사용해 주세요. 본 문서의 예시에서 `https://toapis.com` 을 `https://toapis.cn` 로 바꿔 주세요.

* Create a new API token via API
* Customize token name and expiration time
* Configure quota limits and model restrictions
* Token key is only returned once upon creation

> [!WARNING]
>
> **Security Notice**
>
> Please securely store the returned token key (`key` field). It is only displayed once upon creation and cannot be retrieved later.

## Authorizations

**Authorization** `string` *required*

All endpoints require Bearer Token authentication

Get your API Key:

Visit the [API Key Management Page](https://toapis.com/console/token) to get your API Key

Add it to the request header:

```
Authorization: Bearer YOUR_API_KEY
```

## Body

**name** `string` *required*

Token name, maximum 50 characters

Example: `"My New Token"`

**expired\_time** `integer` (default: -1)

Token expiration time (Unix timestamp in seconds)

* Set to `-1` for never expires
* Set to a specific timestamp to expire at that time

Example: `1738483200` (2025-02-02 00:00:00 UTC)

**remain\_quota** `integer` (default: 0)

Token remaining quota (internal units)

Conversion: `500000` = \$1 USD

Example: `500000` (equivalent to \$1)

**remain\_credits** `float` (default: 0)

Token remaining credits. If provided, it overrides `remain_quota`

Conversion: `200` credits = \$1 USD = `500000` internal quota

Example: `200` (equivalent to \$1)

**daily\_credits** `float` (default: 0)

Daily token limit in credits. If provided, it is converted to `daily_quota`

Example: `100` (equivalent to \$0.5 daily limit)

**monthly\_credits** `float` (default: 0)

Monthly token limit in credits. If provided, it is converted to `monthly_quota`

Example: `1000` (equivalent to \$5 monthly limit)

**unlimited\_quota** `boolean` (default: false)

Whether the token has unlimited quota

* `true`: Unlimited quota, no restrictions
* `false`: Limited quota, uses `remain_quota` value

Example: `false`

**model\_limits\_enabled** `boolean` (default: false)

Whether to enable model restrictions

* `true`: Enable model restrictions, only models in `model_limits` can be used
* `false`: No model restrictions

Example: `false`

**model\_limits** `string`

List of allowed models (comma-separated)

Only effective when `model_limits_enabled` is `true`

Example: `"gpt-4o,gpt-4o-mini,claude-3-5-sonnet"`

**group** `string`

Token group name

Used to specify the channel group for this token

Example: `"default"`

## 응답

**success** `boolean`

Whether the request was successful

**message** `string`

오류 message (only returned on failure)

**data** `object`

Created token information (returned on success)

**data field details**

**id** `integer`

Token ID

**key** `string`

Token key (only returned once upon creation, please store securely)

Format is a 48-character random string, use with `sk-` prefix

**name** `string`

Token name

**status** `integer`

Token status

* `1`: Enabled
* `2`: Disabled
* `3`: Expired
* `4`: Quota exhausted

**user\_id** `integer`

Owner user ID

**created\_time** `integer`

Creation time (Unix timestamp)

**expired\_time** `integer`

Expiration time (Unix timestamp), -1 means never expires

**remain\_quota** `integer`

Remaining quota

**remain\_credits** `float`

Remaining credits, calculated with `1 USD = 200 credits`

**unlimited\_quota** `boolean`

Whether it has unlimited quota

**used\_quota** `integer`

Used quota

**used\_credits** `float`

Used credits

**daily\_credits** `float`

Daily limit in credits

**monthly\_credits** `float`

Monthly limit in credits

**model\_limits\_enabled** `boolean`

Whether model limits are enabled

**model\_limits** `string`

모델 limits list

**group** `string`

Group name

```bash cURL theme={null}
curl --request POST \
  --url 'https://toapis.com/v1/tokens' \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '{
    "name": "My New Token",
    "expired_time": -1,
    "remain_credits": 200,
    "unlimited_quota": false
  }'
```

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

API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'

headers = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
}

def create_token():
    payload = {
        'name': 'My New Token',
        'expired_time': -1,  # Never expires
        'remain_credits': 200,
        'unlimited_quota': False
    }

    response = requests.post(
        f'{API_BASE}/v1/tokens',
        headers=headers,
        json=payload
    )
    data = response.json()

    if data.get('success'):
        token_data = data['data']
        print(f"Token created successfully!")
        print(f"Token name: {token_data['name']}")
        print(f"Token key: sk-{token_data['key']}")
        print("Please store this key securely, it's only shown once!")
    else:
        print(f"Creation failed: {data.get('message')}")

    return data

create_token()
```

```javascript JavaScript theme={null}
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

async function createToken() {
  const payload = {
    name: 'My New Token',
    expired_time: -1, // Never expires
    remain_credits: 200,
    unlimited_quota: false
  };

  const response = await fetch(`${API_BASE}/v1/tokens`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(payload)
  });

  const data = await response.json();

  if (data.success) {
    const tokenData = data.data;
    console.log('Token created successfully!');
    console.log(`Token name: ${tokenData.name}`);
    console.log(`Token key: sk-${tokenData.key}`);
    console.log("Please store this key securely, it's only shown once!");
  } else {
    console.error('Creation failed:', data.message);
  }

  return data;
}

createToken();
```

```go Go theme={null}
package main

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

type CreateTokenRequest struct {
    Name           string  `json:"name"`
    ExpiredTime    int64   `json:"expired_time"`
    RemainCredits  float64 `json:"remain_credits"`
    UnlimitedQuota bool    `json:"unlimited_quota"`
}

type TokenResponse struct {
    Success bool   `json:"success"`
    Message string `json:"message,omitempty"`
    Data    struct {
        Id             int    `json:"id"`
        Key            string `json:"key"`
        Name           string `json:"name"`
        Status         int    `json:"status"`
        CreatedTime    int64  `json:"created_time"`
        ExpiredTime    int64  `json:"expired_time"`
        RemainQuota    int    `json:"remain_quota"`
        UnlimitedQuota bool   `json:"unlimited_quota"`
    } `json:"data"`
}

func main() {
    url := "https://toapis.com/v1/tokens"
    apiKey := "sk-xxxxxxxxxxxxxxxxxxxxxx"

    payload := CreateTokenRequest{
        Name:           "My New Token",
        ExpiredTime:    -1,
        RemainCredits:  200,
        UnlimitedQuota: false,
    }

    jsonData, _ := json.Marshal(payload)

    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

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

    body, _ := ioutil.ReadAll(resp.Body)

    var result TokenResponse
    json.Unmarshal(body, &result)

    if result.Success {
        fmt.Println("Token created successfully!")
        fmt.Printf("Token name: %s\n", result.Data.Name)
        fmt.Printf("Token key: sk-%s\n", result.Data.Key)
        fmt.Println("Please store this key securely, it's only shown once!")
    } else {
        fmt.Printf("Creation failed: %s\n", result.Message)
    }
}
```

```php PHP theme={null}
<?php

$api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

$payload = [
    'name' => 'My New Token',
    'expired_time' => -1,
    'remain_credits' => 200,
    'unlimited_quota' => false
];

$ch = curl_init('https://toapis.com/v1/tokens');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $api_key",
    "Content-Type: application/json"
]);

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

$data = json_decode($response, true);

if ($data['success']) {
    echo "Token created successfully!\n";
    echo "Token name: " . $data['data']['name'] . "\n";
    echo "Token key: sk-" . $data['data']['key'] . "\n";
    echo "Please store this key securely, it's only shown once!\n";
} else {
    echo "Creation failed: " . $data['message'] . "\n";
}
?>
```

```json 200 - Success theme={null}
{
  "success": true,
  "message": "",
  "credits_per_usd": 200,
  "data": {
    "id": 123,
    "user_id": 456,
    "key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "status": 1,
    "name": "My New Token",
    "created_time": 1738483200,
    "accessed_time": 1738483200,
    "expired_time": -1,
    "remain_quota": 500000,
    "remain_credits": 200,
    "unlimited_quota": false,
    "used_quota": 0,
    "used_credits": 0,
    "daily_credits": 0,
    "monthly_credits": 0,
    "model_limits_enabled": false,
    "model_limits": "",
    "group": "",
    "cross_group_retry": false
  }
}
```

```json 200 - Name Too Long theme={null}
{
  "success": false,
  "message": "令牌名称过长"
}
```

```json 401 - Authentication Failed theme={null}
{
  "error": {
    "code": 401,
    "message": "Authentication failed, please check your API key",
    "type": "authentication_error"
  }
}
```

```json 429 - Rate Limited theme={null}
{
  "error": {
    "code": 429,
    "message": "Too many requests, please try again later",
    "type": "rate_limit_error"
  }
}
```

## Use Cases

* Automate creation of multiple API tokens
* Create separate tokens for different applications or services
* Batch manage token lifecycle through scripts

> [!NOTE]
>
> **Token Key Format**
>
> The `key` field returned upon success is a 48-character random string. When using, add the `sk-` prefix for the complete format: `sk-xxxxxxxx...`

> [!TIP]
>
> **Best Practices**
>
> * Create different tokens for different purposes for easier tracking and management
> * Set reasonable expiration times and rotate tokens regularly
> * Enable model limits if you only need access to specific models for enhanced security

## Common 오류

| 오류 Message | Cause | Solution |
| - | - | - |
| 令牌名称过长 | Name exceeds 50 characters | Use a shorter token name |
| 生成令牌失败 | Internal system error | Retry later or contact support |
| 인증 failed | API Key is invalid or expired | Check if the API Key is correct |

> [!WARNING]
>
> **Security Notice**
>
> * The created token key is only returned once in the response, save it immediately
> * Do not hardcode API Keys in client-side code
> * Always use HTTPS in production
> * Create separate tokens for each application for easier management and revocation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.