Create a role with the Java SDK
permit.api.roles.create() creates a role, with optional permissions, in your Permit environment. This reference is for Java developers who define role-based access control (RBAC) roles from code. The examples assume an initialized Permit client named permit, as set up in Check permissions with the Java SDK.
Signature
RoleRead create(RoleCreate roleData) throws IOException, PermitApiError, PermitContextError
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
roleData | RoleCreate | Yes | The role to create. The fields are listed in RoleCreate fields. |
RoleCreate fields
The RoleCreate(key, name) constructor sets the two required fields. Set the optional fields with the with...() builder methods.
| Field | Builder method | Type | Required | Description |
|---|---|---|---|---|
key | withKey() | String | Yes | A URL-friendly name (slug) of the role. Use the key instead of the role ID (UUID) in later calls. |
name | withName() | String | Yes | The display name of the role. |
description | withDescription() | String | No | What the role represents or which permissions it grants. |
permissions | withPermissions() | List<String> | No | The permissions the role grants, in resource:action format (for example document:read). |
attributes | withAttributes() | HashMap<String, Object> | No | Key-value metadata about the role. |
extends | withExtends() | List<String> | No | Keys of roles that this role extends. The role inherits all permissions of the listed roles. |
grantedTo | withGrantedTo() | DerivedRoleBlockEdit | No | Derived role rules applied to this role. |
Example
The example creates an admin role that grants the create and read actions on the document resource. The example also uses java.util.ArrayList and java.util.Arrays.
import io.permit.sdk.openapi.models.RoleCreate;
import io.permit.sdk.openapi.models.RoleRead;
import java.util.ArrayList;
import java.util.Arrays;
RoleRead admin = permit.api.roles.create(
new RoleCreate("admin","Admin")
.withDescription("an admin role")
.withPermissions(
new ArrayList<>(Arrays.asList("document:create", "document:read"))
)
);
Return value
create() returns a RoleRead object (io.permit.sdk.openapi.models.RoleRead) with the created role.
Exceptions
All exception classes except IOException are in the io.permit.sdk.api package.
| Exception | Thrown when |
|---|---|
IOException | The HTTP request to the Permit API fails, for example because of a network error. |
PermitApiError | The Permit API returns an error status code. getResponseCode() returns the HTTP status code and getRawResponse() returns the response body. |
PermitContextError | The SDK context does not include an environment, for example because the API key is scoped to an organization or project. |