# pai-code

Part of **PAI**

# Platform for AI (PAI) Code Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| List Code Sources | Synchronous | Queries a list of code source configurations with support for paging, sorting, and filtering. Returns detailed information about each code source, including ID, display name, repository URL, and timestamps. |
| Publish Code Source | Synchronous | Publishes a private code source, making it public within a workspace. This API allows users to update the visibility of a code source by publishing it. |

## API Calling Patterns

### Authentication
The primary authentication method is **Bearer Token** via the `Authorization` header.

- Use the header: `Authorization: Bearer <your_api_key>`
- Store your API key in the environment variable: `DASHSCOPE_API_KEY`
- While other Alibaba Cloud authentication methods (e.g., AccessKey) may be supported in broader contexts, all documented examples for this domain use Bearer Token with `DASHSCOPE_API_KEY`.

### Service Endpoint
The APIs use region-specific base URLs:

- China regions: `https://api.aliyun.com/api/AIWorkSpace/2021-02-04`
- International regions: `https://api.alibabacloud.com/api/AIWorkSpace/2021-02-04`

Common regions include `cn-hangzhou`, `cn-shanghai`, and `cn-beijing`. The exact endpoint path depends on the operation (e.g., `/ListCodeSources`, `/PublishCodeSource`).

### Synchronous Pattern
Both available functions use a **Synchronous** calling pattern:
1. Send an HTTP request (GET for listing, PUT for publishing) to the appropriate endpoint.
2. Include required parameters either as query string (GET) or in the request body/path (PUT).
3. Receive a complete JSON response immediately upon success or error.
4. Parse the response to extract results or handle errors.

No polling or streaming is involved—each call completes in one round trip.

## Parameter Reference

### List Code Sources

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| DisplayName | string | false | — | — | The display name of the code source configuration. Fuzzy match is supported. |
| PageNumber | integer | false | 1 | range 1 to infinity | The page number. The value starts from 1. |
| PageSize | integer | false | 20 | max 100 | The number of entries to return on each page. |
| SortBy | string | false | GmtCreateTime | one of: GmtModifyTime, DisplayName, CodeSourceId, GmtCreateTime | The field to use for sorting. |
| Order | string | false | ASC | one of: ASC, DESC | The sort order. |
| WorkspaceId | string | false | — | — | The workspace ID. For more information, see ListWorkspaces. |

### Publish Code Source

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| CodeSourceId | string | true | — | — | The ID of the code source to publish. For more information, see ListCodeSources. |

## Code Examples

### List Code Sources - Bash - All Regions

```bash
curl -X GET 'https://api.aliyun.com/api/AIWorkSpace/2021-02-04/ListCodeSources?WorkspaceId=1234&PageNumber=1&PageSize=10&SortBy=GmtModifyTime&Order=desc' \
-H 'Authorization: Bearer $DASHSCOPE_API_KEY' \
-H 'Content-Type: application/json'
```

### Publish Code Source - HTTP Request - All Regions

```http
PUT /api/AIWorkSpace/2021-02-04/PublishCodeSource HTTP/1.1
Host: api.aliyun.com
Authorization: Bearer <your-api-key>
Content-Type: application/json

{
  "CodeSourceId": "code-a797*******"
}
```

### List Code Sources with Filtering - Python - cn-hangzhou

```python
import os
import requests

api_key = os.getenv("DASHSCOPE_API_KEY")
url = "https://api.aliyun.com/api/AIWorkSpace/2021-02-04/ListCodeSources"
params = {
    "WorkspaceId": "1234",
    "DisplayName": "MyProject",
    "PageNumber": 1,
    "PageSize": 20,
    "SortBy": "GmtCreateTime",
    "Order": "ASC"
}
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.get(url, params=params, headers=headers)
print(response.json())
```

### Publish Code Source Using Requests - Python - International

```python
import os
import requests

api_key = os.getenv("DASHSCOPE_API_KEY")
url = "https://api.alibabacloud.com/api/AIWorkSpace/2021-02-04/PublishCodeSource"
payload = {"CodeSourceId": "code-a797*******"}
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.put(url, json=payload, headers=headers)
print(response.json())
```

## Response Format

```json
{
  "CodeSources": [
    {
      "CodeSourceId": "code-202**********",
      "DisplayName": "MyCodeSourceName1",
      "Description": "code source of dlc examples",
      "CodeRepo": "https://code.aliyun.com/****",
      "CodeBranch": "master",
      "CodeCommit": "44da10**********",
      "CodeRepoUserName": "user",
      "CodeRepoAccessToken": "",
      "Accessibility": "PUBLIC",
      "UserId": "1157290171663117",
      "WorkspaceId": "1234",
      "GmtCreateTime": "2021-01-18T12:52:15Z",
      "GmtModifyTime": "2021-01-18T12:52:15Z",
      "MountPath": "/root/code/"
    }
  ],
  "TotalCount": 2,
  "RequestId": "5A14FA81-DD4E-******-6343FE44B941"
}
```

**Key Fields**:
- `CodeSources` — Array of code source objects containing repository details, IDs, and metadata
- `TotalCount` — Total number of code sources matching the query (for pagination)
- `RequestId` — Unique identifier for the API request, useful for debugging

For `PublishCodeSource`, the response includes:
- `CodeSourceId` — The ID of the published code source
- `RequestId` — Unique request identifier

## Error Handling

| Error Code | Description | Recommended Action |
|------------|-------------|---------------------|
| 400 | Invalid request parameters. Check that all required fields are provided and values are valid. | Validate input parameters against constraints (e.g., PageSize ≤ 100, valid SortBy values). |
| 401 | Unauthorized: The user does not have sufficient permissions to perform this operation. | Ensure your API key has the necessary permissions for the target workspace. |
| 403 | Access denied. Ensure the user has proper permissions to list code sources in the specified workspace. | Verify IAM policies or workspace membership; contact administrator if needed. |
| 404 | Workspace not found. Verify the WorkspaceId is correct and the workspace exists. | Confirm the `WorkspaceId` using the ListWorkspaces API. |
| 500 | Internal server error. Retry the request after a short delay. If the issue persists, contact support. | Implement retry logic with exponential backoff; log `RequestId` for support. |

### Rate Limits & Retry
- **ListCodeSources**: 100 QPS per user; maximum 100 records per request
- **PublishCodeSource**: 100 QPS
- Use exponential backoff (e.g., 1s, 2s, 4s delays) on 5xx errors
- Respect the `Retry-After` header if present (though not explicitly documented, standard practice applies)

## Environment Requirements

- Set your API key: `export DASHSCOPE_API_KEY=your_api_key_here`
- Required packages (for Python examples): `requests` (`pip install requests`)
- No specific runtime version requirements are documented, but Python 3.6+ is recommended for compatibility

## FAQ

Q: How do I obtain a `CodeSourceId` to use with `PublishCodeSource`?
A: First call `ListCodeSources` to retrieve available code sources and their IDs. Only private code sources can be published.

Q: Can I filter code sources by Git branch or commit?
A: No. Filtering is only supported by `DisplayName` (fuzzy match), `WorkspaceId`, and sorting fields. Branch and commit appear in the response but are not queryable.

Q: What happens if I publish a code source that is already public?
A: The API will likely succeed idempotently, but the documentation does not specify behavior for redundant publishes. Check the `Accessibility` field in `ListCodeSources` first to avoid unnecessary calls.

Q: Are international and China endpoints interchangeable?
A: No. Use `api.aliyun.com` for Alibaba Cloud accounts in mainland China and `api.alibabacloud.com` for global accounts. Using the wrong endpoint may result in authentication or routing errors.

Q: Is the `CodeRepoAccessToken` returned in plaintext?
A: Yes, but it is masked (empty string) in the example response. In practice, sensitive credentials should be handled securely and may not be returned depending on permissions.

## Pricing & Billing

### Billing Model
Per-request billing: each API call (successful or failed) counts as one request.

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| default | 0.0001 CNY/request | 0.0001 CNY/request |
| default (Publish) | 0.001 CNY/request | 0.001 CNY/request |

### Free Tier
1,000 free requests per month for both `ListCodeSources` and `PublishCodeSource`.

### Usage Limits
- 100 QPS per user across both APIs
- `ListCodeSources`: maximum 100 records per request

### Billing Notes
Billing is based on the number of API calls made, regardless of success or failure. Each invocation of `ListCodeSources` or `PublishCodeSource` consumes one request unit.