Skip to content

Modify



POST /api/v1/workspace/accesskey/{ak_uuid}/modify

Overview

Modify the API Key name and replace its direct role associations.

Before You Call and Usage Steps

An External credential with w permission is required. name is mandatory; even if you only want to change roles, pass the current name. Omitting roleUUIDs keeps the original role associations; an explicit array replaces the complete target set rather than adding incrementally. Do not use [] to revoke permissions; when there are no valid associations, authorization can fall back to wsAdmin. To revoke credentials, delete the Key. Including owner converts the Key to an Owner-only Key, ignores other target roles, and allows at most one such Key per workspace; switching from Owner to a non-Owner array removes the Owner flag. Keys created from an Agent source cannot be modified. The name/Owner flag is committed first, and roles are then validated and updated, so a 400 such as InvalidRoleUUID may already have changed the name or Owner flag; read the details first to verify the current state before retrying. This operation does not rotate ak/sk.

Route Parameters

Parameter Type Required Description
ak_uuid string Y API Key record UUID (usually with the wsak_ prefix), not the ak/sk call credential; this External path locates the record across workspaces by UUID, so verify workspaceUUID before executing.
Example: wsak_example001
How to obtain or fill in: Get it from content.data[].uuid in the API Key list or from content.uuid returned on successful creation.

Request Headers

Parameter Type Required Description
X-Df-SVersion string Signature version for the original path and request body; it cannot be omitted while continuing to use the algorithm on this page.
Example: v20240417
How to obtain or fill in: The examples on this page use this fixed version, which matches the example signing algorithm.
X-Df-Access-Key string Y The list endpoint in this module accepts 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; a workspace OpenAPI Key cannot be used.
X-Df-Signature string Y Perform HMAC-SHA256 over the uppercase method, nonce, original full path, timestamp, and original UTF-8 request body joined by spaces, and take the hex digest.
Example: <hmac-sha256-hex>
How to obtain or fill in: Compute it with the matching SK as described in External API Signature Authentication; see the complete runnable template below.
X-Df-Timestamp string Y Must fall within the signature validity window configured for the site; do not reuse the example timestamp.
Example: 1785427200
How to obtain or fill in: Use str(int(time.time())) to generate the current Unix seconds string when sending.
X-Df-Nonce string Y Temporary serial number; when resending after a failure, also generate a new value and recompute the signature.
Example: 97d275ee9f774315a7885ba7347acbd9
How to obtain or fill in: Regenerate uuid.uuid4().hex for each request.

Body Request Parameters

Parameter Type Required Description
roleUUIDs[*] string A single role UUID string; the role must be within the allowed range of the target workspace.
Example: role_example001
How to obtain or fill in: Get the actual role uuid of the target workspace from the workspace role list. Prefer an explicit least-privilege custom role or built-in roles such as readOnly/general.
name string Y Required, up to 256 characters. To keep the name when changing roles, you must still pass the current value; it cannot be null.
Allows null: False
Maximum length: 256
Example: 示例API Key新名称
How to obtain or fill in: Get the current name from API Key details, and use a new name only when needed.
roleUUIDs array Optional. Omitting it keeps the original associations; an explicit array replaces them entirely; [] clears the associations but authorization may fall back to administrator, so it cannot be used to revoke permissions. owner has special privilege-escalation semantics, and null is invalid.
Allows null: False
Example: ["role_example001"]
How to obtain or fill in: Get the actual role uuid of the target workspace from the workspace role list. Prefer an explicit least-privilege custom role or built-in roles such as readOnly/general.

Additional Parameter Notes

Use the site-level External API AK/SK; for signing, see External API Signature Authentication. The workspace API Key generated on this page is not the same set of credentials as the External signing credential. External currently returns the AK/SK in plaintext and does not apply the masking policy of the front-end page; all response examples use placeholder values, so store actual responses as credentials. After modification, clear the authentication cache corresponding to the AK/SK so that subsequent requests obtain permissions again under the new roles; cache processing failures may occur after the database commit.

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/wsak_example001/modify'
query = {}
data = {'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 the AK/SK.
    raise SystemExit(1)
except (URLError, TimeoutError):
    print('Request result unknown. Verify the current state of the target and whether the write has already occurred before deciding whether to re-sign and retry; do not automatically repeat write requests.')
    raise SystemExit(1)
print(json.dumps(payload, ensure_ascii=False, indent=2))

Response

HTTP 200 with a unified application/json envelope; the business result is in content. External does not automatically add declaration, and list pagination is in content.pageInfo.

Field Type Description
content.id integer or null Internal record sequence number; API calls use uuid. A creation snapshot taken before flush may have this field as null.
content.uuid string API Key record UUID, different from the ak/sk call credential.
content.status integer Key status: 0 enabled, 2 disabled, 3 deleted. List/details return only 0; deletion can also handle disabled Keys that have not been deleted.
content.creator string Identity that created the record; External creations are usually external.
content.updator string Identity that updated the record; may be empty if never modified.
content.createAt integer Creation time in Unix seconds.
content.deleteAt integer Deletion time in Unix seconds; usually -1 when not deleted.
content.updateAt integer Update time in Unix seconds; usually -1 if never modified.
content.name string Display name of the API Key.
content.ak string Plaintext workspace Access Key call credential, usable for OpenAPI authentication in that workspace; it 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 UUID of the bound account; empty string for manual workspace Keys. For account-bound Keys, the effective permissions must be confirmed against the account roles.
content.createdWay string Source identifier, such as manual, user, or agent; the list excludes all Keys whose accountUUID is non-empty.
content.businessType string System business type identifier; usually empty for manual Keys.
content.isSystem integer Whether it is a system built-in Key; queries and operations in this module filter out system Keys.
content.isOwnerRole integer Whether it is an Owner-only Key: 1 yes, 0 no; at most one undeleted Owner Key per workspace.
content.remark string Existing remark; the public create/modify parameters of this External API do not include remark.
content.isBurnAfterReading integer Retained burn-after-reading flag; this module does not destroy the credential after reading, so do not rely on it to revoke credentials.
content.callCount integer or null Persistent cumulative call count; statistics are asynchronous and not real-time. A creation snapshot taken before flush may be null.
content.lastCallAt integer or null Last call time in Unix seconds; usually -1 means no record yet. A creation snapshot may be null.
content.roleInfo array of objects Role association summary returned in this response. Branches such as Owner conversion may return []; combine it with isOwnerRole and call the details endpoint to confirm the effective roles/permissions.
content.roleInfo[].uuid string Role UUID.
content.roleInfo[].name string Role name.
{
  "code": 200,
  "content": {
    "id": 1001,
    "uuid": "wsak_example001",
    "status": 0,
    "creator": "external",
    "updator": "external",
    "createAt": 1785427200,
    "deleteAt": -1,
    "updateAt": 1785427200,
    "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": 0,
    "lastCallAt": -1,
    "roleInfo": [
      {
        "uuid": "role_example001",
        "name": "示例最小权限角色"
      }
    ]
  },
  "errorCode": "",
  "message": "",
  "success": true,
  "traceId": "TRACE-EXAMPLE"
}

Error Responses

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 state may already have been saved, so you must query the current state first before deciding the next step.

HTTP Status errorCode Trigger Condition Message or Response Description Handling
406 ft.ParameterValidationFailed A request field is missing, or a field value violates the declared validation conditions Parameter parsing failed Check the parameter location, field name, type, and value.
400 ft.RequestJsonFormatError The request JSON syntax is invalid Request JSON format error Fix the JSON according to content.reason, line, and column.
400 ft.JsonFormatError The 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.
404 ft.AKNotExistOrDelete The UUID has no corresponding active non-system API Key, or the Key has been deleted/disabled The specified AK does not exist, or has been deleted Obtain the target uuid from the list again; note that the list does not show account-bound Keys, and system built-in Keys cannot be managed through this entry point.
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; to change an existing Key, use modify, and do not treat repeated creation as 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 role list. The modify endpoint may already have saved the name or Owner flag, so you must read the current state first even after this 400.
400 ft.AgentWorkspaceAKCanNotModify The target is a Key with createdWay=agent that is bound to an account API Keys bound to an agent cannot be modified Manage it through the corresponding Agent/account capability; do not use this endpoint to rename it or change its roles.
500 ft.InternalServerError A database, cache invalidation, audit, or unhandled field exception occurred Internal error Retain the traceId and check the Key's current name, roles, and status. Data may be committed before the failure, so do not treat a 500 alone as meaning the change did not take effect.

Feedback

Is this page helpful?