Create¶
POST /api/v1/workspace/accesskey/add
Overview¶
Create an API Key for the specified workspace and associate it with roles.
Before Calling and Usage Steps¶
Requires an External credential with w permission. First confirm the workspace is active and obtain the target role UUID. It is recommended to always explicitly provide non-empty roleUUIDs; omitting them creates an administrator Key, and [] may also result in administrator permissions due to authorization fallback. Creation is not idempotent by name; duplicate names return an error. After a timeout, query the list first to confirm whether the Key was created. Typically, use non-Owner roles. The current External implementation also accepts owner: it only creates an Owner-only Key and ignores other role values; a workspace can have at most one undeleted Owner Key. On success, it returns the new credential and role summary. Creation snapshot fields such as id/call statistics may be null, and persisted information can subsequently be obtained from the details.
Request Headers¶
| 参数名 | 类型 | 必选 | 说明 |
|---|---|---|---|
| X-Df-SVersion | string | Signature version for the original path and request body; cannot be omitted and then continue to use the algorithm on this page. Example: v20240417How to obtain or fill in: This page uses this fixed version, which matches the example signature algorithm. |
|
| X-Df-Access-Key | string | Y | The list in this module can use r or w permission; all other endpoints, including GET details, require an External credential with w permission. Example: <external-access-key>How to obtain or fill in: Assigned by the site administrator as an External API AK; workspace OpenAPI Keys cannot be used. |
| X-Df-Signature | string | Y | Concatenate the uppercase method, nonce, original full path, timestamp, and raw UTF-8 request body with spaces, then compute HMAC-SHA256 and use the hex digest. Example: <hmac-sha256-hex>How to obtain or fill in: Calculate using the matching SK as described in External API Signature Authentication; see the complete runnable template below. |
| X-Df-Timestamp | string | Y | Must be within the signature validity window configured for the site; do not reuse the example time. Example: 1785427200How to obtain or fill in: When sending, use str(int(time.time())) to generate the current Unix seconds string. |
| X-Df-Nonce | string | Y | Temporary nonce; when resending after a failure, also generate a new value and recompute the signature. Example: 97d275ee9f774315a7885ba7347acbd9How to obtain or fill in: Generate a new uuid.uuid4().hex for each request. |
Body Request Parameters¶
| 参数名 | 类型 | 必选 | 说明 |
|---|---|---|---|
| roleUUIDs[*] | string | A single role UUID string; the role must be within the allowed range of the target workspace. Example: role_example001How to obtain or fill in: Obtain the actual role UUID for the target workspace from Workspace Role List. It is recommended to use an explicit least-privilege custom role or built-in roles such as readOnly/general. |
|
| name | string | Y | Required display name, maximum 256 characters; provide a non-empty string that is not duplicated. Null allowed: False Maximum length: 256 Example: 示例只读API KeyHow to obtain or fill in: First use API Key List to check existing names in the target workspace. |
| roleUUIDs | array | Optional; if omitted, defaults to the wsAdmin administrator role. It is recommended to explicitly pass a verified non-empty least-privilege role. An explicit [] does not produce a Key without permissions: authorization can fall back to wsAdmin when there is no valid role association, so an empty array cannot be used to revoke permissions. null is invalid. Null allowed: False Example: ["role_example001"]How to obtain or fill in: Obtain the actual role UUID for the target workspace from Workspace Role List. It is recommended to use an explicit least-privilege custom role or built-in roles such as readOnly/general. |
|
| workspaceUUID | string | Y | Required UUID of the target workspace for creation; must be an existing workspace with active status=0; cannot be omitted, empty, or null. Null allowed: False Example: wksp_example001How to obtain or fill in: Obtain and verify the target workspace from content.data[].uuid in the Workspace List. |
Additional Parameter Notes¶
Use site-level External API AK/SK; for the signature method, see External API Signature Authentication. The workspace API Key generated on this page and the External signing credential are not the same set of credentials. External currently returns the AK/SK in plaintext and does not apply the masking policy of the frontend page; all response examples use placeholder values, and the actual response should be kept as a credential. This API has no public input parameters such as accountUUID, createdWay, remark, or burn-after-reading, and cannot be used to create a Key bound to an account.
Request Example¶
import hashlib
import hmac
import json
import time
import uuid
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
# Replace with the target site address and the External API AK/SK assigned by the administrator.
server = "https://external-api.guance.com"
access_key = "<external-access-key>"
secret_key = "<external-secret-key>"
method = 'POST'
path = '/api/v1/workspace/accesskey/add'
query = {}
data = {'workspaceUUID': 'wksp_example001', 'name': '示例只读API Key', 'roleUUIDs': ['role_example001']}
full_path = path + ("?" + urlencode(query) if query else "")
body = "" if data is None else json.dumps(data, ensure_ascii=False, separators=(",", ":"))
timestamp = str(int(time.time()))
nonce = uuid.uuid4().hex
string_to_sign = " ".join([method, nonce, full_path, timestamp, body])
signature = hmac.new(secret_key.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
"X-Df-Access-Key": access_key,
"X-Df-Timestamp": timestamp,
"X-Df-Nonce": nonce,
"X-Df-Signature": signature,
"X-Df-SVersion": "v20240417",
}
if data is not None:
headers["Content-Type"] = "application/json"
request = Request(server + full_path, data=None if data is None else body.encode("utf-8"), headers=headers, method=method)
try:
with urlopen(request, timeout=30) as result:
payload = json.loads(result.read().decode("utf-8"))
except HTTPError as error:
print("HTTP", error.code, error.read().decode("utf-8")) # Handle by errorCode, content, and traceId; do not output AK/SK.
raise SystemExit(1)
except (URLError, TimeoutError):
print('请求结果未知,请先核对目标当前状态及是否已经写入,再决定是否重新签名重试;不要自动重复写请求。')
raise SystemExit(1)
print(json.dumps(payload, ensure_ascii=False, indent=2))
Response¶
HTTP 200, application/json unified envelope, with business results in content; External does not automatically add declaration, and list pagination is in content.pageInfo.
| 字段 | 类型 | 说明 |
|---|---|---|
| content.id | integer 或 null | Internal record sequence number; API calls use uuid. The creation snapshot is obtained before flush, so this field may be null. |
| content.uuid | string | UUID of the API Key record, different from the calling credentials ak/sk. |
| content.status | integer | Key status: 0 enabled, 2 disabled, 3 deleted. List/details return only 0; deletion can also handle an undeleted disabled Key. |
| content.creator | string | Creator identity; for External creation, usually external. |
| content.updator | string | Updater identity; may be empty if not modified. |
| content.createAt | integer | Creation Unix seconds. |
| content.deleteAt | integer | Deletion Unix seconds; usually -1 if not deleted. |
| content.updateAt | integer | Update Unix seconds; usually -1 if not yet modified. |
| content.name | string | API Key display name. |
| content.ak | string | Plaintext workspace Access Key calling credential; can be used for OpenAPI authentication in that workspace and is not the X-Df-Access-Key of this External request. |
| content.sk | string | Plaintext workspace Secret Key; store it as a sensitive credential. It is not the matching SK for this External request. |
| content.workspaceUUID | string | UUID of the workspace it belongs to. |
| content.accountUUID | string | Bound account UUID; for manual workspace Keys this is an empty string. The effective permissions of an account-bound Key must be confirmed based on the account roles. |
| content.createdWay | string | Source identifier, such as manual, user, or agent; the list excludes all Keys with a non-empty accountUUID. |
| content.businessType | string | System business type identifier; usually empty for manual Keys. |
| content.isSystem | integer | Whether it is a system built-in Key; queries/operations in this module filter system Keys. |
| content.isOwnerRole | integer | Whether it is an Owner-only Key, 1 yes, 0 no; a workspace can have at most one undeleted Owner Key. |
| content.remark | string | Existing remark; the public create/modify parameters of this External interface do not include remark. |
| content.isBurnAfterReading | integer | Retained burn-after-reading flag; this module does not destroy after reading, and it should not be relied on to revoke credentials. |
| content.callCount | integer 或 null | Persistent cumulative call count; asynchronous statistics, not a real-time count. The creation snapshot may be null before flush. |
| content.lastCallAt | integer 或 null | Last call Unix seconds; usually -1 means no record yet; the creation snapshot may be null. |
| content.roleInfo | 对象数组 | Summary of roles associated at creation; an explicit [] may return [], which cannot be used to determine that effective permissions are empty. |
| content.roleInfo[].uuid | string | Role UUID. |
| content.roleInfo[].name | string | Role name. |
{
"code": 200,
"content": {
"id": null,
"uuid": "wsak_example001",
"status": 0,
"creator": "external",
"updator": "",
"createAt": 1785427200,
"deleteAt": -1,
"updateAt": -1,
"name": "示例只读API Key",
"ak": "<workspace-api-key>",
"sk": "<workspace-secret-key>",
"workspaceUUID": "wksp_example001",
"accountUUID": "",
"createdWay": "manual",
"businessType": "",
"isSystem": 0,
"isOwnerRole": 0,
"remark": "",
"isBurnAfterReading": 0,
"callCount": null,
"lastCallAt": null,
"roleInfo": [
{
"uuid": "role_example001",
"name": "示例最小权限角色"
}
]
},
"errorCode": "",
"message": "",
"success": true,
"traceId": "TRACE-EXAMPLE"
}
Error Response¶
For authentication, rate limiting, and common request errors, see Common Error Definitions.
The table below lists confirmed request and business branches. Ordinary database/cache/audit 5xx errors are globally wrapped as ft.InternalServerError; when a write endpoint returns an error, the name, Owner flag, roles, or deletion status may already have been saved. You must query the current state before deciding the next step.
| HTTP 状态 | errorCode | 触发条件 | 消息或响应说明 | 处理方式 |
|---|---|---|---|---|
| 406 | ft.ParameterValidationFailed | Request field missing, or field value violates the declared validation conditions | Parameter parsing failed | Check the parameter location, field name, type, and value. |
| 400 | ft.RequestJsonFormatError | Invalid request JSON syntax | Request JSON format error | Fix the JSON according to content.reason, line, and column. |
| 400 | ft.JsonFormatError | JSON top level is not an object | Some json file format error | Use a JSON object; do not use an array or null as the entire request body. |
| 401 | ft.WKSPNotExistOrReleased | Target workspace does not exist or is not active status=0 | Workspace does not exist/or has been released | Select a valid workspace from the Workspace List. |
| 400 | ft.AKNameRepeat | An undeleted API Key with the same name already exists in the target workspace | An AK with the same name already exists | Query the name first; if you need to change an existing Key, use modify. Do not treat repeated creation as an idempotent success. |
| 400 | ft.AKOnwerRepeat | Another undeleted Owner Key already exists in the same workspace | An Owner AK already exists | Check the existing Owner Key first; do not create multiple Owner Keys through repeated creation or simultaneous privilege escalation. |
| 400 | ft.InvalidRoleUUID | The role UUID is not in the valid role set of the target workspace | Invalid role UUID: {} | Select again from the target workspace's role list. The modify endpoint may have already saved the name or Owner flag; after this 400 is returned, you must also read the current state first. |
| 500 | ft.InternalServerError | Database, cache failure, audit, or unhandled field exception | Internal error | Retain the traceId and check the Key's current name, roles, and status. Data may have been committed before the failure; do not assume it did not take effect based solely on the 500. |