# bailian-access

Part of **BAILIAN**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Manage API access credentials, keys, and network security](../../intent/bailian-manage-security/SKILL.md). If you're unsure which path to take, check the routing skill first.

# Alibaba Cloud Model Studio Platform, Security, and Operations

## Capabilities Overview

| Sub-capability | API Pattern | Description |
|----------------|-------------|-------------|
| Temporary API Key | Synchronous | Generate temporary API keys for secure, short-term access. |
| Async Task Management | Synchronous | Query, cancel, and manage asynchronous tasks programmatically. |
| RSA Encryption | Synchronous | Obtain RSA public keys to encrypt sensitive model inputs and secure API payloads. |

## API Calling Modes

### Authentication

The primary and recommended authentication method for all platform and security APIs is the **Bearer Token** method using your permanent API key.

- **Header Format**: `Authorization: Bearer $DASHSCOPE_API_KEY`
- **Environment Variable**: `DASHSCOPE_API_KEY`

Ensure your permanent API key is securely stored in the `DASHSCOPE_API_KEY` environment variable before making requests. You can obtain a permanent API key from the Alibaba Cloud Model Studio Console under **API Key Management**.

### Service Endpoints

Endpoints vary based on the specific function and your deployment region.

**Temporary API Key Endpoints:**
- China (Default): `https://dashscope.aliyuncs.com/api/v1/tokens`
- International: `https://dashscope-intl.aliyuncs.com/api/v1/tokens`
- US: `https://dashscope-us.aliyuncs.com/api/v1/tokens`
- Hong Kong: `https://cn-hongkong.dashscope.aliyuncs.com/api/v1/tokens`
- Europe (Frankfurt): `https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/tokens`

**Async Task Management & RSA Encryption Endpoints:**
- Global / All Regions: `https://dashscope.aliyuncs.com/api/v1/...`

### Synchronous API Pattern

All APIs in this domain follow a standard Synchronous calling flow:
1. **Construct Request**: Build an HTTP request (GET or POST) with the required headers, query parameters, or JSON body.
2. **Send Request**: Execute the request to the designated endpoint.
3. **Receive Response**: The server processes the request immediately and returns a JSON response containing either the requested data (e.g., token, task status, public key) or an error object.

## Parameter Reference

### Temporary API Key

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| expire_in_seconds | number | No | 60 | Range: 1 to 1800 | Custom time-to-live (TTL) for the temporary API key in seconds. |

### Async Task Management

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| Authorization | string | Yes | - | - | API key in the format `Bearer sk-xxx`. |
| task_id | string | Yes (for single query/cancel) | - | - | The unique identifier of the task to query or cancel. |
| start_time | string | No | - | Format: YYYYMMDDhhmmss | Query start time. Defaults to 24 hours before end_time, or the last 24 hours. Max range: 24 hours. |
| end_time | string | No | - | Format: YYYYMMDDhhmmss | Query end time. Defaults to 24 hours after start_time. Max range: 24 hours. |
| model_name | string | No | - | - | Filter tasks by the specific model name used. |
| status | string | No | - | PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED, UNKNOWN | Filter tasks by their current execution status. |
| page_no | integer | No | 1 | - | The page number of the results to return. |
| page_size | integer | No | 10 | - | The number of entries per page. |

### RSA Encryption

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| Authorization | string | Yes | - | - | The API key for authentication. |

## Code Examples

### Generate Temporary API Key - Bash - China

```bash
curl -X POST "https://dashscope.aliyuncs.com/api/v1/tokens?expire_in_seconds=1800" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
```
*Note: For other regions, replace the base URL with the appropriate endpoint (e.g., `https://dashscope-intl.aliyuncs.com/api/v1/tokens` for International, `https://dashscope-us.aliyuncs.com/api/v1/tokens` for US, or `https://cn-hongkong.dashscope.aliyuncs.com/api/v1/tokens` for Hong Kong).*

### Query Single Async Task - Bash - All Regions

```bash
curl -X GET 'https://dashscope.aliyuncs.com/api/v1/tasks/73205176-xxxx-xxxx-xxxx-16bd5d902219' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

### Batch Query Async Tasks - Bash - All Regions

```bash
curl -X GET 'https://dashscope.aliyuncs.com/api/v1/tasks/?start_time=20231220000000&end_time=20231220235959&status=SUCCEEDED' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

### Cancel Pending Async Task - Bash - All Regions

```bash
curl -X POST 'https://dashscope.aliyuncs.com/api/v1/tasks/73205176-xxxx-xxxx-xxxx-16bd5d902219/cancel' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

### Obtain RSA Public Key - Bash - All Regions

```bash
curl -X GET 'https://dashscope.aliyuncs.com/api/v1/public-keys/latest' \
--header 'Authorization: Bearer $DASHSCOPE_API_KEY'
```

## Response Format

### Temporary API Key Success Response

```json
{
  "token": "st-****",
  "expires_at": 1744080369
}
```

**Key Fields**:
- `token` — The generated temporary API key string.
- `expires_at` — The Unix timestamp (in seconds) indicating when the token will expire.

### Async Task Management Success Response

```json
{
  "request_id": "45ac7f13-xxxx-xxxx-xxxx-e03c35068d83",
  "output": {
    "task_id": "73205176-xxxx-xxxx-xxxx-16bd5d902219",
    "task_status": "SUCCEEDED",
    "submit_time": "2023-12-20 21:36:31.896",
    "scheduled_time": "2023-12-20 21:36:39.009",
    "end_time": "2023-12-20 21:36:45.913",
    "results": [
      {
        "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx1.png"
      },
      {
        "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx2.png"
      },
      {
        "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx3.png"
      },
      {
        "code": "DataInspectionFailed",
        "message": "Output data may contain inappropriate content."
      }
    ],
    "task_metrics": {
      "TOTAL": 4,
      "SUCCEEDED": 3,
      "FAILED": 1
    }
  },
  "usage": {
    "image_count": 3
  }
}
```

**Key Fields**:
- `request_id` — Unique identifier for the API request.
- `output.task_id` — The unique identifier of the queried task.
- `output.task_status` — Current state of the task (e.g., PENDING, RUNNING, SUCCEEDED, FAILED).
- `output.results` — Array containing the output URLs or specific error messages for failed sub-tasks.
- `output.task_metrics` — Summary counts of TOTAL, SUCCEEDED, and FAILED sub-tasks.
- `usage` — Resource consumption metrics, such as `image_count`.

### RSA Encryption Success Response

```json
{
  "request_id": "bcb3***",
  "data": {
    "public_key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnojrB579xgPQN5f46SvoRAiQBPWBaPzWh7hp51fWI+OsQk7KqH0qMcw8i0eK5rfOvJIPujOQgnes1ph9/gKAst9NzXVIl9JJYUSPtzTvOabhp4yvS3KBf9g3xHYVjYgW33SOY74Ue/tgbCXn717rV6gXb4sVvq9XK/1BrDcGbEOQEZEgBTFkm/g3lpWLQtACwwqHffoA9eQtkkz15ZFKosAgbR8LedfIvxAl2zk15REzxXiRcFgc9/tLF0U1t2Sxt9FkQefxYwn6EZawTsRJvf4kqF3MaPdTcDbOp0iSNvCl2qzPSf/F+Oll2CUM1tFAEu81oa4l0WaDR3UtvqOtyQIDAQAB",
    "public_key_id": "1"
  }
}
```

**Key Fields**:
- `request_id` — Unique identifier for the API request.
- `data.public_key` — The RSA public key string used for encrypting sensitive payloads.
- `data.public_key_id` — The identifier for the specific public key version.

## Error Handling

| Code | Description | Recommended Action |
|------|-------------|--------------------|
| InvalidApiKey | The provided API key is invalid. | Ensure the `DASHSCOPE_API_KEY` environment variable is correctly set and the key has not been revoked or expired. |
| UnsupportedOperation | Task cancellation failed. | Only tasks in the `PENDING` state can be canceled. Check the task status before attempting cancellation. |
| Throttling.RateQuota | Requests rate limit exceeded. | Implement exponential backoff and retry the request after a short delay. |
| InvalidParameter | Required parameter(s) missing or invalid. | Check the request parameters and ensure all required fields are provided in the correct format. |

### Rate Limits & Retry

- **Async Task Management**: Limited to **20 QPS** (Queries Per Second) per Alibaba Cloud account. This limit includes all RAM (Resource Access Management) users under the account.
- **Retry Strategy**: If you encounter a `Throttling.RateQuota` error, implement an exponential backoff strategy. Wait for 1 second, then 2 seconds, then 4 seconds, etc., before retrying the request.

## Pricing & Billing

### Billing Model

- **Temporary API Keys**: Free of charge.
- **Async Task Management & RSA Encryption**: Billed per request. Actual costs for async tasks vary by the underlying model used and are billed based on task duration and resource usage.

### Billing Notes

- Temporary API keys are free to generate but inherit the permissions and rate limits of the parent permanent API key.
- Completed asynchronous tasks are retained for **24 hours**. After this expiration period, the system automatically deletes the task data and results. Ensure you download or process task results within this window.

## FAQ

**Q: What is the maximum lifespan of a temporary API key?**
A: A temporary API key can be configured to last anywhere from 1 second up to a maximum of 1800 seconds (30 minutes). If not specified, it defaults to 60 seconds.

**Q: Can I cancel an asynchronous task that is already running?**
A: No. You can only cancel tasks that are currently in the `PENDING` state. If a task has transitioned to `RUNNING`, `SUCCEEDED`, or `FAILED`, the cancellation request will return an `UnsupportedOperation` error.

**Q: How long can I query the results of a completed asynchronous task?**
A: Completed task data and results are retained for exactly 24 hours. After this period, the data is permanently deleted by the system.

**Q: Why do I need to fetch an RSA public key before calling certain models?**
A: For models that process highly sensitive data, the platform requires the input payload to be encrypted in transit. You must fetch the latest RSA public key, use it to encrypt your sensitive inputs (often in combination with AES encryption), and pass the encrypted payload to the model API.

**Q: Do temporary API keys have different rate limits than permanent ones?**
A: No. Temporary API keys inherit the exact same permissions, quotas, and rate limits as the parent permanent API key used to generate them.

## Source Documents

- `Generate a temporary API key_5591120.xdita`
- `Manage asynchronous tasks_5324095.xdita`
- `Obtain an RSA public key_5150470.xdita`