> ## Documentation Index
> Fetch the complete documentation index at: https://unkey.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Set key roles

> Replace all roles on a key with the specified set in a single atomic operation.

Use this to synchronize with external systems, reset roles to a known state, or apply standardized role templates. Direct permissions are never affected.

**Important**: Changes take effect immediately with up to 30-second edge propagation.

**Required Permissions**

Your root key must have one of the following permissions:
- `api.*.update_key` (to update keys in any API)
- `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

Invalidates the key cache for immediate effect, and makes role changes available for verification within 30 seconds across all regions.




## OpenAPI

````yaml https://spec.speakeasy.com/unkey/unkey/openapi-json-with-code-samples post /v2/keys.setRoles
openapi: 3.1.0
info:
  description: >-
    Unkey's API provides programmatic access for all resources within our
    platform.



    ### Authentication

    #

    This API uses HTTP Bearer authentication with root keys. Most endpoints
    require specific permissions associated with your root key. When making
    requests, include your root key in the `Authorization` header:

    ```

    Authorization: Bearer unkey_xxxxxxxxxxx

    ```


    All responses follow a consistent envelope structure that separates
    operational metadata from actual data. This design provides several
    benefits:

    - Debugging: Every response includes a unique requestId for tracing issues

    - Consistency: Predictable response format across all endpoints

    - Extensibility: Easy to add new metadata without breaking existing
    integrations

    - Error Handling: Unified error format with actionable information


    ### Success Response Format:

    ```json

    {
      "meta": {
        "requestId": "req_123456"
      },
      "data": {
        // Actual response data here
      }
    }

    ```


    The meta object contains operational information:

    - `requestId`: Unique identifier for this request (essential for support)


    The data object contains the actual response data specific to each endpoint.


    ### Paginated Response Format:

    ```json

    {
      "meta": {
        "requestId": "req_123456"
      },
      "data": [
        // Array of results
      ],
      "pagination": {
        "cursor": "next_page_token",
        "hasMore": true
      }
    }

    ```


    The pagination object appears on list endpoints and contains:

    - `cursor`: Token for requesting the next page

    - `hasMore`: Whether more results are available


    ### Error Response Format:

    ```json

    {
      "meta": {
        "requestId": "req_2c9a0jf23l4k567"
      },
      "error": {
        "detail": "The resource you are attempting to modify is protected and cannot be changed",
        "status": 403,
        "title": "Forbidden",
        "type": "https://unkey.com/docs/errors/unkey/application/protected_resource"
      }
    }

    ```


    Error responses include comprehensive diagnostic information:

    - `title`: Human-readable error summary

    - `detail`: Specific description of what went wrong

    - `status`: HTTP status code

    - `type`: Link to error documentation

    - `errors`: Array of validation errors (for 400 responses)


    This structure ensures you always have the context needed to debug issues
    and take corrective action.
  title: Unkey API
  version: 2.0.0
servers:
  - url: https://api.unkey.com
security:
  - rootKey: []
tags:
  - description: Analytics query operations
    name: analytics
  - description: API management operations
    name: apis
  - description: Deployment operations
    name: deploy
  - description: Identity management operations
    name: identities
  - description: API key management operations
    name: keys
  - description: Health check operations
    name: liveness
  - description: Permission and role management operations
    name: permissions
  - description: Customer Portal session management
    name: portal
  - description: Rate limiting operations
    name: ratelimit
paths:
  /v2/keys.setRoles:
    post:
      tags:
        - keys
      summary: Set key roles
      description: >
        Replace all roles on a key with the specified set in a single atomic
        operation.


        Use this to synchronize with external systems, reset roles to a known
        state, or apply standardized role templates. Direct permissions are
        never affected.


        **Important**: Changes take effect immediately with up to 30-second edge
        propagation.


        **Required Permissions**


        Your root key must have one of the following permissions:

        - `api.*.update_key` (to update keys in any API)

        - `api.<api_id>.update_key` (to update keys in a specific API)


        **Side Effects**


        Invalidates the key cache for immediate effect, and makes role changes
        available for verification within 30 seconds across all regions.
      operationId: keys.setRoles
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/V2KeysSetRolesRequestBody'
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/V2KeysSetRolesResponseBody'
          description: >-
            Roles set successfully. Returns all roles currently assigned to the
            key.
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BadRequestErrorResponse'
          description: Bad request
        '401':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UnauthorizedErrorResponse'
          description: Unauthorized
        '403':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ForbiddenErrorResponse'
          description: Forbidden
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotFoundErrorResponse'
          description: Not found
        '429':
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/TooManyRequestsErrorResponse'
          description: Too Many Requests
        '500':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InternalServerErrorResponse'
          description: Internal server error
      security:
        - rootKey: []
      x-codeSamples:
        - lang: go
          label: Go (SDK)
          source: "package main\n\nimport(\n\t\"context\"\n\t\"os\"\n\tunkey \"github.com/unkeyed/sdks/api/go/v2\"\n\t\"github.com/unkeyed/sdks/api/go/v2/models/components\"\n\t\"log\"\n)\n\nfunc main() {\n    ctx := context.Background()\n\n    s := unkey.New(\n        unkey.WithSecurity(os.Getenv(\"UNKEY_ROOT_KEY\")),\n    )\n\n    res, err := s.Keys.SetRoles(ctx, components.V2KeysSetRolesRequestBody{\n        KeyID: \"key_2cGKbMxRyIzhCxo1Idjz8q\",\n        Roles: []string{},\n    })\n    if err != nil {\n        log.Fatal(err)\n    }\n    if res.V2KeysSetRolesResponseBody != nil {\n        // handle response\n    }\n}"
        - lang: python
          label: Python (SDK)
          source: |-
            from unkey.py import Unkey


            with Unkey(
                root_key="<YOUR_BEARER_TOKEN_HERE>",
            ) as unkey:

                res = unkey.keys.set_roles(key_id="key_2cGKbMxRyIzhCxo1Idjz8q", roles=[])

                # Handle response
                print(res)
        - lang: typescript
          label: Typescript (SDK)
          source: |-
            import { Unkey } from "@unkey/api";

            const unkey = new Unkey({
              rootKey: process.env["UNKEY_ROOT_KEY"] ?? "",
            });

            async function run() {
              const result = await unkey.keys.setRoles({
                keyId: "key_2cGKbMxRyIzhCxo1Idjz8q",
                roles: [],
              });

              console.log(result);
            }

            run();
components:
  schemas:
    V2KeysSetRolesRequestBody:
      type: object
      required:
        - keyId
        - roles
      properties:
        keyId:
          type: string
          minLength: 3
          maxLength: 255
          pattern: ^[a-zA-Z0-9_]+$
          description: >
            Specifies which key gets the complete role replacement using the
            database identifier returned from createKey.

            Do not confuse this with the actual API key string that users
            include in requests.

            This is a wholesale replacement operation that removes all existing
            roles not included in the request.

            Role changes take effect immediately but may take up to 30 seconds
            to propagate across all regions.
          example: key_2cGKbMxRyIzhCxo1Idjz8q
        roles:
          type: array
          maxItems: 100
          description: >
            Replaces all existing role assignments with this complete list of
            roles.

            This is a wholesale replacement operation, not an incremental update
            like add/remove operations.


            Providing an empty array removes all direct role assignments from
            the key.

            All roles must already exist in the workspace - roles cannot be
            created automatically.

            Invalid role references cause the entire operation to fail
            atomically, ensuring consistent state.
          items:
            type: string
            pattern: ^[a-zA-Z0-9_:\-\.\*]+$
            minLength: 3
            maxLength: 255
            description: Specify the role by name.
      additionalProperties: false
    V2KeysSetRolesResponseBody:
      type: object
      required:
        - meta
        - data
      properties:
        meta:
          $ref: '#/components/schemas/Meta'
        data:
          $ref: '#/components/schemas/V2KeysSetRolesResponseData'
    BadRequestErrorResponse:
      type: object
      required:
        - meta
        - error
      properties:
        meta:
          $ref: '#/components/schemas/Meta'
        error:
          $ref: '#/components/schemas/BadRequestErrorDetails'
      description: >-
        Error response for invalid requests that cannot be processed due to
        client-side errors. This typically occurs when request parameters are
        missing, malformed, or fail validation rules. The response includes
        detailed information about the specific errors in the request, including
        the location of each error and suggestions for fixing it. When receiving
        this error, check the 'errors' array in the response for specific
        validation issues that need to be addressed before retrying.
    UnauthorizedErrorResponse:
      type: object
      required:
        - meta
        - error
      properties:
        meta:
          $ref: '#/components/schemas/Meta'
        error:
          $ref: '#/components/schemas/BaseError'
      description: >-
        Error response when authentication has failed or credentials are
        missing. This occurs when:

        - No authentication token is provided in the request

        - The provided token is invalid, expired, or malformed

        - The token format doesn't match expected patterns


        To resolve this error, ensure you're including a valid root key in the
        Authorization header.
    ForbiddenErrorResponse:
      type: object
      required:
        - meta
        - error
      properties:
        meta:
          $ref: '#/components/schemas/Meta'
        error:
          $ref: '#/components/schemas/BaseError'
      description: >-
        Error response when the provided credentials are valid but lack
        sufficient permissions for the requested operation. This occurs when:

        - The root key doesn't have the required permissions for this endpoint

        - The operation requires elevated privileges that the current key lacks

        - Access to the requested resource is restricted based on workspace
        settings


        To resolve this error, ensure your root key has the necessary
        permissions or contact your workspace administrator.
    NotFoundErrorResponse:
      type: object
      required:
        - meta
        - error
      properties:
        meta:
          $ref: '#/components/schemas/Meta'
        error:
          $ref: '#/components/schemas/BaseError'
      description: >-
        Error response when the requested resource cannot be found. This occurs
        when:

        - The specified resource ID doesn't exist in your workspace

        - The resource has been deleted or moved

        - The resource exists but is not accessible with current permissions


        To resolve this error, verify the resource ID is correct and that you
        have access to it.
    TooManyRequestsErrorResponse:
      type: object
      required:
        - meta
        - error
      properties:
        meta:
          $ref: '#/components/schemas/Meta'
        error:
          $ref: '#/components/schemas/BaseError'
      description: >-
        Error response when the client has sent too many requests in a given
        time period. This occurs when you've exceeded a rate limit or quota for
        the resource you're accessing.


        The rate limit resets automatically after the time window expires. To
        avoid this error:

        - Implement exponential backoff when retrying requests

        - Cache results where appropriate to reduce request frequency

        - Check the error detail message for specific quota information

        - Contact support if you need a higher quota for your use case
    InternalServerErrorResponse:
      type: object
      required:
        - meta
        - error
      properties:
        meta:
          $ref: '#/components/schemas/Meta'
        error:
          $ref: '#/components/schemas/BaseError'
      description: >-
        Error response when an unexpected error occurs on the server. This
        indicates a problem with Unkey's systems rather than your request.


        When you encounter this error:

        - The request ID in the response can help Unkey support investigate the
        issue

        - The error is likely temporary and retrying may succeed

        - If the error persists, contact Unkey support with the request ID
    Meta:
      type: object
      required:
        - requestId
      properties:
        requestId:
          description: >-
            A unique id for this request. Always include this ID when contacting
            support about a specific API request. This identifier allows Unkey's
            support team to trace the exact request through logs and diagnostic
            systems to provide faster assistance.
          example: req_123
          type: string
      additionalProperties: false
      description: >-
        Metadata object included in every API response. This provides context
        about the request and is essential for debugging, audit trails, and
        support inquiries. The `requestId` is particularly important when
        troubleshooting issues with the Unkey support team.
    V2KeysSetRolesResponseData:
      type: array
      description: >-
        Complete list of all roles now directly assigned to the key after the
        set operation has completed.


        The response includes:

        - The comprehensive, updated set of roles (reflecting the complete
        replacement)

        - Both ID and name for each role for easy reference


        Important notes:

        - This response shows the final state after the complete replacement

        - If you provided an empty array in the request, this will also be empty

        - This only shows direct role assignments on the key

        - Role permissions are not expanded in this response - use keys.getKey
        for complete details

        - An empty array indicates the key now has no roles assigned at all
      items:
        $ref: '#/components/schemas/Role'
    BadRequestErrorDetails:
      allOf:
        - $ref: '#/components/schemas/BaseError'
        - type: object
          properties:
            errors:
              description: >-
                List of individual validation errors that occurred in the
                request. Each error provides specific details about what failed
                validation, where the error occurred in the request, and
                suggestions for fixing it. This granular information helps
                developers quickly identify and resolve multiple issues in a
                single request without having to make repeated API calls.
              items:
                $ref: '#/components/schemas/ValidationError'
              type: array
          required:
            - errors
      description: >-
        Extended error details specifically for bad request (400) errors. This
        builds on the BaseError structure by adding an array of individual
        validation errors, making it easy to identify and fix multiple issues at
        once.
    BaseError:
      properties:
        detail:
          description: >-
            A human-readable explanation specific to this occurrence of the
            problem. This provides detailed information about what went wrong
            and potential remediation steps. The message is intended to be
            helpful for developers troubleshooting the issue.
          example: Property foo is required but is missing.
          type: string
        status:
          description: >-
            HTTP status code that corresponds to this error. This will match the
            status code in the HTTP response. Common codes include `400` (Bad
            Request), `401` (Unauthorized), `403` (Forbidden), `404` (Not
            Found), `409` (Conflict), and `500` (Internal Server Error).
          example: 404
          format: int
          type: integer
        title:
          description: >-
            A short, human-readable summary of the problem type. This remains
            constant from occurrence to occurrence of the same problem and
            should be used for programmatic handling.
          example: Not Found
          type: string
        type:
          description: >-
            A URI reference that identifies the problem type. This provides a
            stable identifier for the error that can be used for documentation
            lookups and programmatic error handling. When followed, this URI
            should provide human-readable documentation for the problem type.
          example: https://unkey.com/docs/errors/unkey/resource/not_found
          type: string
      required:
        - title
        - detail
        - status
        - type
      type: object
      additionalProperties: false
      description: >-
        Base error structure following Problem Details for HTTP APIs (RFC 7807).
        This provides a standardized way to carry machine-readable details of
        errors in HTTP response content.
    Role:
      type: object
      properties:
        id:
          type: string
          description: >
            The unique identifier for this role within Unkey's system.

            Generated automatically when the role is created and used to
            reference this role in API operations.

            Always begins with 'role_' followed by alphanumeric characters and
            underscores.
          example: role_1234567890abcdef
        name:
          type: string
          description: >
            The human-readable name for this role that describes its function.

            Should be descriptive enough for administrators to understand what
            access this role provides.

            Use clear, semantic names that reflect the job function or
            responsibility level.

            Names must be unique within your workspace to avoid confusion during
            role assignment.
          example: support.readonly
        description:
          type: string
          description: >
            Optional detailed explanation of what this role encompasses and what
            access it provides.

            Helps team members understand the role's scope, intended use cases,
            and security implications.

            Include information about what types of users should receive this
            role and what they can accomplish.

            Not visible to end users - this is for internal documentation and
            access control audits.
          example: >-
            Provides read-only access for customer support representatives to
            view user accounts and support tickets
          x-go-type-skip-optional-pointer: true
          x-go-type-skip-optional-pointer-with-omitzero: true
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/Permission'
          maxItems: 100
          description: >
            Complete list of permissions currently assigned to this role.

            Each permission grants specific access rights that will be inherited
            by any keys or users assigned this role.

            Use this list to understand the full scope of access provided by
            this role.

            Permissions can be added or removed from roles without affecting the
            role's identity or other properties.

            Empty array indicates a role with no permissions currently assigned.
          x-go-type-skip-optional-pointer: true
          x-go-type-skip-optional-pointer-with-omitzero: true
      required:
        - id
        - name
      additionalProperties: false
    ValidationError:
      additionalProperties: false
      properties:
        location:
          description: >-
            JSON path indicating exactly where in the request the error
            occurred. This helps pinpoint the problematic field or parameter.
            Examples include:

            - 'body.name' (field in request body)

            - 'body.items[3].tags' (nested array element)

            - 'path.apiId' (path parameter)

            - 'query.limit' (query parameter)

            Use this location to identify exactly which part of your request
            needs correction.
          type: string
          example: body.permissions[0].name
        message:
          description: >-
            Detailed error message explaining what validation rule was violated.
            This provides specific information about why the field or parameter
            was rejected, such as format errors, invalid values, or constraint
            violations.
          type: string
          example: Must be at least 3 characters long
        fix:
          description: >-
            A human-readable suggestion describing how to fix the error. This
            provides practical guidance on what changes would satisfy the
            validation requirements. Not all validation errors include fix
            suggestions, but when present, they offer specific remediation
            advice.
          type: string
          example: >-
            Ensure the name uses only alphanumeric characters, underscores, and
            hyphens
      required:
        - location
        - message
      type: object
      description: >-
        Individual validation error details. Each validation error provides
        precise information about what failed, where it failed, and how to fix
        it, enabling efficient error resolution.
    Permission:
      type: object
      properties:
        id:
          type: string
          minLength: 3
          maxLength: 255
          pattern: ^[a-zA-Z0-9_]+$
          description: >
            The unique identifier for this permission within Unkey's system.

            Generated automatically when the permission is created and used to
            reference this permission in API operations.

            Always begins with 'perm_' followed by alphanumeric characters and
            underscores.
          example: perm_1234567890abcdef
        name:
          type: string
          minLength: 1
          maxLength: 512
          description: >
            The human-readable name for this permission that describes its
            purpose.

            Should be descriptive enough for developers to understand what
            access it grants.

            Use clear, semantic names that reflect the resources or actions
            being permitted.

            Names must be unique within your workspace to avoid confusion and
            conflicts.
          example: users.read
        slug:
          pattern: ^[a-zA-Z0-9_:\-\.\*]+$
          type: string
          minLength: 1
          maxLength: 512
          description: The unique URL-safe identifier for this permission.
          example: users-read
        description:
          type: string
          maxLength: 512
          description: >
            Optional detailed explanation of what this permission grants access
            to.

            Helps team members understand the scope and implications of granting
            this permission.

            Include information about what resources can be accessed and what
            actions can be performed.

            Not visible to end users - this is for internal documentation and
            team clarity.
          example: Allows reading user profile information and account details
          x-go-type-skip-optional-pointer: true
          x-go-type-skip-optional-pointer-with-omitzero: true
      required:
        - id
        - name
        - slug
  securitySchemes:
    rootKey:
      bearerFormat: root key
      description: >-
        Unkey uses API keys (root keys) for authentication. These keys authorize
        access to management operations in the API.

        To authenticate, include your root key in the Authorization header of
        each request:

        ```

        Authorization: Bearer unkey_123

        ```

        Root keys have specific permissions attached to them, controlling what
        operations they can perform. Key permissions follow a hierarchical
        structure with patterns like `resource.resource_id.action` (e.g.,
        `apis.*.create_key`, `apis.*.read_api`).

        Security best practices:

        - Keep root keys secure and never expose them in client-side code

        - Use different root keys for different environments

        - Rotate keys periodically, especially after team member departures

        - Create keys with minimal necessary permissions following least
        privilege principle

        - Monitor key usage with audit logs.
      scheme: bearer
      type: http

````