# HTTP API

> Manage Cloud Code scripts using raw HTTP APIs and the Admin API.

您可以使用原始 HTTP API 来管理 Cloud Code 脚本。

## 使用 API##using-the-api

* [Admin API](https://services.docs.unity.com/cloud-code-admin/v1#tag/cloud-code-scripts) 文档包含管理操作（例如创建、读取、更新和删除脚本）的详细描述。
* [Client API](https://services.docs.unity.com/cloud-code/v1#section/overview) 文档包含面向客户端的操作（例如运行脚本）的详细描述。

这两个 API 文档都包含有关身份验证、终端以及请求和响应格式的信息，并提供相关示例。您可以采用 OpenAPI 格式下载它们，并参考它们来设置您自己的自动化过程。

要使用 Admin API，请使用[服务帐户](https://services.docs.unity.com/docs/service-account-auth/)进行身份验证。

### Authorization 标头##authorization-header

要对请求进行身份验证，请使用[基本身份验证](../authentication#cloud-code-admin-api-basic-authentication))。创建一个服务帐户，对 `<KEY_ID>:<SECRET_KEY>` 进行 base64 编码，然后将其用作 `Authorization` 标头的值。

```text
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>' \
```

### 部署脚本##deploy-scripts

您可以通过发送以下请求来创建脚本：

```bash
curl 'https://services.api.unity.com/cloud-code/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>' \
--data '{
    "name": "test-script",
    "type": "API",
    "code": "module.exports = () => {return \"Result from standalone API script\";}",
    "language": "JS"
}'
```

为了使脚本可供游戏客户端使用，必须发布脚本：

```bash
curl --request POST 'https://services.api.unity.com/cloud-code/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts/<SCRIPT_NAME>/publish' \
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>'
```

每次发布时，脚本版本都会递增。成功的响应可能如下所示：

```json
{
    "version": 1,
    "datePublished": "2023-06-23T10:39:20Z"
}
```

无法发布自上次发布以来未发生任何更改的脚本。

### 更新脚本##update-scripts

您可以通过发送以下请求来更新脚本代码和/或参数：

```bash
curl --request PATCH 'https://services.api.unity.com/cloud-code/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts/<SCRIPT_NAME>' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>' \
--data '{
    "params": [
        {
            "name": "parameter",
            "type": "STRING",
            "required": false
        }
    ],
     "code": "module.exports = () => {return \"Updated result from standalone API script\";}"
}'
```

为了使脚本的更新版本可供游戏客户端使用，必须再次发布，从而创建版本 2。

```json
{
    "version": 2,
    "datePublished": "2023-06-23T10:40:00Z"
}
```

### 回滚脚本##rollback-scripts

如果您发布了脚本，而又对新版本不满意，则可以通过发送含指定版本号的请求来回滚到前一个版本：

```bash
curl --request POST 'https://services.api.unity.com/cloud-code/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts/<SCRIPT_NAME>/publish' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>'
--data '{
    "version": 1
}'
```

现在，第一个脚本版本重新发布为版本 3：

```json
{
    "version": 3,
    "datePublished": "2023-06-23T10:50:00Z"
}
```

### 获取脚本##retrieve-scripts

要查看脚本的内容，可以发送以下请求：

```bash
curl 'https://services.api.unity.com/cloud-code/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts/<SCRIPT_NAME>' \
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>'
```

响应可能如下所示：

```json
{
  "name": "test",
  "type": "API",
  "language": "JS",
  "activeScript": {
    "code": "module.exports=async (cloudCode) =>{cloudCode.logger.info('this message confirms that the logging client is functional!'); return cloudCode.params.someThing;}",
    "params": [
      {
        "name": "someThing",
        "type": "STRING",
        "required": true
      }
    ],
    "version": 2,
    "datePublished": "2021-07-23T16:08:35Z"
  },
  "versions": [
    {
      "code": "module.exports=async (cloudCode) =>{cloudCode.logger.info('this message confirms that the logging client is functional!'); return cloudCode.params.someThing;}",
      "params": [
        {
          "name": "someThing",
          "type": "STRING",
          "required": true
        }
      ],
      "isDraft": true,
      "version": null,
      "dateUpdated": "2021-07-23T15:59:32Z"
    },
    {
      "code": "module.exports=async (cloudCode) =>{cloudCode.logger.info('this message confirms that the logging client is functional!'); return cloudCode.params.someThing;}",
      "params": [
        {
          "name": "someThing",
          "type": "STRING",
          "required": true
        }
      ],
      "isDraft": false,
      "version": 2,
      "dateUpdated": "2021-07-23T16:08:35Z",
      "dateCreated": "2021-07-23T16:08:35Z"
    },
    {
      "code": "module.exports=async (cloudCode) =>{cloudCode.logger.info('this message confirms that the logging client is functional!'); return cloudCode.params.someThing;}",
      "params": [
        {
          "name": "someThing",
          "type": "STRING",
          "required": true
        }
      ],
      "isDraft": false,
      "version": 1,
      "dateUpdated": "2021-07-23T15:59:58Z",
      "dateCreated": "2021-07-23T15:59:58Z"
    }
  ],
  "params": [
    {
      "name": "someThing",
      "type": "STRING",
      "required": true
    }
  ]
}
```

响应包含以下信息：

* `name`：脚本的名称。
* `type`：脚本的类型。Cloud Code 脚本仅支持 API 脚本。
* `language`：脚本的语言。Cloud Code 脚本仅支持 JavaScript。

`activeScript` 是指可供游戏客户端使用的当前发布的脚本版本。此部分包含脚本代码和参数、版本号和发布日期。

`versions` 数组包含脚本的所有版本，包括当前发布的版本、工作副本和任何以前发布的版本。此工作副本是包含最新更改但尚不可供游戏客户端使用的脚本版本。对于此版本，属性 `isDraft` 设置为 `true`，且其 `version` 为 null。下次发送发布请求时，将发布此工作副本。

要查看已创建的所有脚本，可以发送以下请求：

```bash
curl 'https://services.api.unity.com/cloud-code/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts' \
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>'
```

此列表响应可能如下所示：

```json
{
    "results": [
        {
            "name": "script",
            "language": "JS",
            "type": "API",
            "published": true,
            "lastPublishedDate": "2022-03-08T12:37:48Z",
            "lastPublishedVersion": 40
        },
        {
            "name": "test",
            "language": "JS",
            "type": "API",
            "published": true,
            "lastPublishedDate": "2023-06-20T15:14:58Z",
            "lastPublishedVersion": 4
        }
    ],
    "links": {
        "next": null
    }
}
```

响应中包含已创建的所有脚本的快速概览。要使用分页功能，可以使用查询参数来缩小结果的范围，并获取指向下一页结果的链接。

```bash
curl 'https://services.api.unity.com/cloud-code/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts?limit=2' \
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>'
```

下一个链接可能如下所示：

```json
{
  "links": {
        "next": "/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts?after=<SCRIPT_NAME>"
    }
}
```

### 删除脚本##delete-script

要删除脚本，可以发送以下请求：

```bash
curl --request DELETE 'https://services.api.unity.com/cloud-code/v1/projects/<PROJECT_ID>/environments/<ENVIRONMENT_ID>/scripts/<SCRIPT_NAME>' \
--header 'Authorization: Basic <SERVICE_ACCOUNT_CREDENTIALS_ENCODED>'
```

空的响应表示删除成功。
