Skip to main content

Create a role with the Go SDK

Permit.Api.Roles.Create() creates a role in the environment that your API key belongs to. This reference is for Go developers who define role-based access control (RBAC) roles from backend code. After you create a role, assign it to users with Users.AssignRole.

Roles.Create signature

func (r *Roles) Create(ctx context.Context, roleCreate models.RoleCreate) (*models.RoleRead, error)

Roles.Create parameters

ParameterTypeRequiredDescription
ctxcontext.ContextYesThe context of the request.
roleCreatemodels.RoleCreateYesThe role to create. Build it with models.NewRoleCreate(key, name).

RoleCreate fields

FieldTypeRequiredDescription
KeystringYesA URL-friendly name of the role (a slug). You use the key to refer to the role in later calls instead of the role ID (a UUID).
NamestringYesThe name of the role.
Description*stringNoWhat the role represents, or which permissions it grants. Set it with SetDescription().
Permissions[]stringNoThe permissions the role grants, each in the format <resource-key>:<action-key>, such as document:read. Set them with SetPermissions().
Extends[]stringNoThe keys of roles that this role extends. The role inherits all the permissions of those roles. Set them with SetExtends().
Attributesmap[string]stringNoKey-value metadata about the role. Set it with SetAttributes().

Example: create a role with Roles.Create

The example uses a client named Permit, created with permit.NewPermit() as shown in Check permissions with the Go SDK, and a ctx of type context.Context.

Build the RoleCreate struct with the key role-key, the name role-name, and the read and write permissions on the resource resource-key:

roleCreate := models.NewRoleCreate("role-key", "role-name")
roleCreate.SetPermissions([]string{"resource-key:read", "resource-key:write"})

Pass the struct to Roles.Create:

role, err := Permit.Api.Roles.Create(ctx, *roleCreate)

Roles.Create return value and errors

On success, Roles.Create returns a *models.RoleRead with the role's Key, Id, Name, Description, Permissions, and Extends.

If the call fails, err holds an errors.PermitError from the github.com/permitio/permit-golang/pkg/errors package. Its StatusCode field has the HTTP status, and its ErrorCode field has one of these codes:

ErrorCodeCause
UnprocessableEntityErrorHTTP 422: a field failed validation.
Unauthorized, ForbiddenAccessHTTP 401 or 403: the API key is invalid or has no access to the environment.
UnexpectedErrorA server error (HTTP 5xx) or a network error.