# Create custom role

POST https://app.launchdarkly.com/api/v2/roles
Content-Type: application/json

Create a new custom role

Reference: https://launchdarkly.com/docs/api/custom-roles/post-custom-role

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/roles:
    post:
      operationId: post-custom-role
      summary: Create custom role
      description: Create a new custom role
      tags:
        - subpackage_customRoles
      parameters:
        - name: Authorization
          in: header
          required: true
          schema:
            type: string
      responses:
        '201':
          description: Custom role response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CustomRole'
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InvalidRequestErrorRep'
        '401':
          description: Invalid access token
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UnauthorizedErrorRep'
        '403':
          description: Forbidden
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ForbiddenErrorRep'
        '409':
          description: Status conflict
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StatusConflictErrorRep'
        '429':
          description: Rate limited
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RateLimitedErrorRep'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CustomRolePost'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    ActionSpecifier:
      type: string
      title: ActionSpecifier
    StatementPostEffect:
      type: string
      enum:
        - allow
        - deny
      description: Whether this statement should allow or deny actions on the resources.
      title: StatementPostEffect
    StatementPost:
      type: object
      properties:
        resources:
          type: array
          items:
            type: string
          description: Resource specifier strings
        notResources:
          type: array
          items:
            type: string
          description: >-
            Targeted resources are the resources NOT in this list. The
            <code>resources</code> field must be empty to use this field.
        actions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: Actions to perform on a resource
        notActions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: >-
            Targeted actions are the actions NOT in this list. The
            <code>actions</code> field must be empty to use this field.
        effect:
          $ref: '#/components/schemas/StatementPostEffect'
          description: >-
            Whether this statement should allow or deny actions on the
            resources.
      required:
        - effect
      title: StatementPost
    StatementPostList:
      type: array
      items:
        $ref: '#/components/schemas/StatementPost'
      title: StatementPostList
    RoleType:
      type: string
      title: RoleType
    ResourceCategory:
      type: string
      title: ResourceCategory
    CustomRolePost:
      type: object
      properties:
        name:
          type: string
          description: A human-friendly name for the custom role
        key:
          type: string
          description: The custom role key
        description:
          type: string
          description: Description of custom role
        policy:
          $ref: '#/components/schemas/StatementPostList'
          description: Resource statements for custom role
        basePermissions:
          $ref: '#/components/schemas/RoleType'
          description: >-
            Base permissions to use for this role. Defaults to no_access (older
            roles defaulted to reader). Recommended to set this to no_access in
            all cases.
        resourceCategory:
          $ref: '#/components/schemas/ResourceCategory'
          description: >-
            The category of resources this role is intended to manage. Can be
            <code>organization</code>, <code>project</code>, or
            <code>any</code>. This field is immutable.
      required:
        - name
        - key
        - policy
      title: CustomRolePost
    Link:
      type: object
      properties:
        href:
          type: string
          description: The URL of the link
        type:
          type: string
          description: The type of the link
      title: Link
    ActionIdentifier:
      type: string
      title: ActionIdentifier
    AccessDeniedReasonEffect:
      type: string
      enum:
        - allow
        - deny
      description: Whether this statement should allow or deny actions on the resources.
      title: AccessDeniedReasonEffect
    AccessDeniedReason:
      type: object
      properties:
        resources:
          type: array
          items:
            type: string
          description: Resource specifier strings
        notResources:
          type: array
          items:
            type: string
          description: >-
            Targeted resources are the resources NOT in this list. The
            <code>resources</code> and <code>notActions</code> fields must be
            empty to use this field.
        actions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: Actions to perform on a resource
        notActions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: >-
            Targeted actions are the actions NOT in this list. The
            <code>actions</code> and <code>notResources</code> fields must be
            empty to use this field.
        effect:
          $ref: '#/components/schemas/AccessDeniedReasonEffect'
          description: >-
            Whether this statement should allow or deny actions on the
            resources.
        role_name:
          type: string
      required:
        - effect
      title: AccessDeniedReason
    AccessDenied:
      type: object
      properties:
        action:
          $ref: '#/components/schemas/ActionIdentifier'
        reason:
          $ref: '#/components/schemas/AccessDeniedReason'
      required:
        - action
        - reason
      title: AccessDenied
    AccessAllowedReasonEffect:
      type: string
      enum:
        - allow
        - deny
      description: Whether this statement should allow or deny actions on the resources.
      title: AccessAllowedReasonEffect
    AccessAllowedReason:
      type: object
      properties:
        resources:
          type: array
          items:
            type: string
          description: Resource specifier strings
        notResources:
          type: array
          items:
            type: string
          description: >-
            Targeted resources are the resources NOT in this list. The
            <code>resources</code> and <code>notActions</code> fields must be
            empty to use this field.
        actions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: Actions to perform on a resource
        notActions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: >-
            Targeted actions are the actions NOT in this list. The
            <code>actions</code> and <code>notResources</code> fields must be
            empty to use this field.
        effect:
          $ref: '#/components/schemas/AccessAllowedReasonEffect'
          description: >-
            Whether this statement should allow or deny actions on the
            resources.
        role_name:
          type: string
      required:
        - effect
      title: AccessAllowedReason
    AccessAllowedRep:
      type: object
      properties:
        action:
          $ref: '#/components/schemas/ActionIdentifier'
        reason:
          $ref: '#/components/schemas/AccessAllowedReason'
      required:
        - action
        - reason
      title: AccessAllowedRep
    Access:
      type: object
      properties:
        denied:
          type: array
          items:
            $ref: '#/components/schemas/AccessDenied'
        allowed:
          type: array
          items:
            $ref: '#/components/schemas/AccessAllowedRep'
      required:
        - denied
        - allowed
      title: Access
    StatementEffect:
      type: string
      enum:
        - allow
        - deny
      description: Whether this statement should allow or deny actions on the resources.
      title: StatementEffect
    Statement:
      type: object
      properties:
        resources:
          type: array
          items:
            type: string
          description: Resource specifier strings
        notResources:
          type: array
          items:
            type: string
          description: >-
            Targeted resources are the resources NOT in this list. The
            <code>resources</code> and <code>notActions</code> fields must be
            empty to use this field.
        actions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: Actions to perform on a resource
        notActions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: >-
            Targeted actions are the actions NOT in this list. The
            <code>actions</code> and <code>notResources</code> fields must be
            empty to use this field.
        effect:
          $ref: '#/components/schemas/StatementEffect'
          description: >-
            Whether this statement should allow or deny actions on the
            resources.
      required:
        - effect
      title: Statement
    AssignedToRep:
      type: object
      properties:
        membersCount:
          type: integer
          description: The number of individual members this role is assigned to
        teamsCount:
          type: integer
          description: The number of teams this role is assigned to
      title: AssignedToRep
    CustomRole:
      type: object
      properties:
        _id:
          type: string
          description: The ID of the custom role
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
        _access:
          $ref: '#/components/schemas/Access'
          description: Details on the allowed and denied actions for this custom role
        description:
          type: string
          description: The description of the custom role
        key:
          type: string
          description: The key of the custom role
        name:
          type: string
          description: The name of the custom role
        policy:
          type: array
          items:
            $ref: '#/components/schemas/Statement'
          description: An array of the policies that comprise this custom role
        basePermissions:
          $ref: '#/components/schemas/RoleType'
          description: >-
            Base permissions to use for this role. Defaults to no_access (older
            roles defaulted to reader). Recommended to set this to no_access in
            all cases.
        resourceCategory:
          $ref: '#/components/schemas/ResourceCategory'
          description: >-
            The category of resources this role is intended to manage. Can be
            <code>organization</code>, <code>project</code>, or
            <code>any</code>. Once set, this field cannot be changed.
        assignedTo:
          $ref: '#/components/schemas/AssignedToRep'
          description: The number of teams and members this role is assigned to
        _presetBundleVersion:
          type: integer
          description: If created from a preset, the preset bundle version
        _presetStatements:
          type: array
          items:
            $ref: '#/components/schemas/Statement'
          description: >-
            If created from a preset, the read-only statements copied from the
            preset
      required:
        - _id
        - _links
        - key
        - name
        - policy
      title: CustomRole
    InvalidRequestErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: InvalidRequestErrorRep
    UnauthorizedErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: UnauthorizedErrorRep
    ForbiddenErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: ForbiddenErrorRep
    StatusConflictErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: StatusConflictErrorRep
    RateLimitedErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: RateLimitedErrorRep
  securitySchemes:
    ApiKey:
      type: apiKey
      in: header
      name: Authorization

```

## SDK Code Examples

```python
import requests

url = "https://app.launchdarkly.com/api/v2/roles"

payload = {
    "name": "Ops team",
    "key": "role-key-123abc",
    "policy": [
        {
            "effect": "allow",
            "resources": ["proj/*:env/production:flag/*"],
            "actions": ["updateOn"]
        }
    ],
    "description": "An example role for members of the ops team",
    "basePermissions": "reader"
}
headers = {
    "Authorization": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://app.launchdarkly.com/api/v2/roles';
const options = {
  method: 'POST',
  headers: {Authorization: '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"name":"Ops team","key":"role-key-123abc","policy":[{"effect":"allow","resources":["proj/*:env/production:flag/*"],"actions":["updateOn"]}],"description":"An example role for members of the ops team","basePermissions":"reader"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://app.launchdarkly.com/api/v2/roles"

	payload := strings.NewReader("{\n  \"name\": \"Ops team\",\n  \"key\": \"role-key-123abc\",\n  \"policy\": [\n    {\n      \"effect\": \"allow\",\n      \"resources\": [\n        \"proj/*:env/production:flag/*\"\n      ],\n      \"actions\": [\n        \"updateOn\"\n      ]\n    }\n  ],\n  \"description\": \"An example role for members of the ops team\",\n  \"basePermissions\": \"reader\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://app.launchdarkly.com/api/v2/roles")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"name\": \"Ops team\",\n  \"key\": \"role-key-123abc\",\n  \"policy\": [\n    {\n      \"effect\": \"allow\",\n      \"resources\": [\n        \"proj/*:env/production:flag/*\"\n      ],\n      \"actions\": [\n        \"updateOn\"\n      ]\n    }\n  ],\n  \"description\": \"An example role for members of the ops team\",\n  \"basePermissions\": \"reader\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://app.launchdarkly.com/api/v2/roles")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"Ops team\",\n  \"key\": \"role-key-123abc\",\n  \"policy\": [\n    {\n      \"effect\": \"allow\",\n      \"resources\": [\n        \"proj/*:env/production:flag/*\"\n      ],\n      \"actions\": [\n        \"updateOn\"\n      ]\n    }\n  ],\n  \"description\": \"An example role for members of the ops team\",\n  \"basePermissions\": \"reader\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://app.launchdarkly.com/api/v2/roles', [
  'body' => '{
  "name": "Ops team",
  "key": "role-key-123abc",
  "policy": [
    {
      "effect": "allow",
      "resources": [
        "proj/*:env/production:flag/*"
      ],
      "actions": [
        "updateOn"
      ]
    }
  ],
  "description": "An example role for members of the ops team",
  "basePermissions": "reader"
}',
  'headers' => [
    'Authorization' => '<apiKey>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://app.launchdarkly.com/api/v2/roles");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"Ops team\",\n  \"key\": \"role-key-123abc\",\n  \"policy\": [\n    {\n      \"effect\": \"allow\",\n      \"resources\": [\n        \"proj/*:env/production:flag/*\"\n      ],\n      \"actions\": [\n        \"updateOn\"\n      ]\n    }\n  ],\n  \"description\": \"An example role for members of the ops team\",\n  \"basePermissions\": \"reader\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "Ops team",
  "key": "role-key-123abc",
  "policy": [
    [
      "effect": "allow",
      "resources": ["proj/*:env/production:flag/*"],
      "actions": ["updateOn"]
    ]
  ],
  "description": "An example role for members of the ops team",
  "basePermissions": "reader"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://app.launchdarkly.com/api/v2/roles")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```