---
type: api
title: Create an API key
description: **All methods and paths for this operation:**
url: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch-serverless/operation/operation-security-create-api-key
resource: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch-serverless/operation/operation-security-create-api-key
products:
  - Elasticsearch Serverless
---

# Create an API key


Availability:

## Paths

- `POST` (also `PUT`) `/_security/api_key`

- [Api key auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch-serverless/authentication#apikeyauth)

## Description

Create an API key for access without requiring basic authentication.

IMPORTANT: If the credential that is used to authenticate this request is an API key, the derived API key cannot have any privileges.
If you specify privileges, the API returns an error.

A successful request returns a JSON structure that contains the API key, its unique id, and its name.
If applicable, it also returns expiration information for the API key in milliseconds.

NOTE: By default, API keys never expire. You can specify expiration information when you create the API keys.

The API keys are created by the Elasticsearch API key service, which is automatically enabled.
To configure or turn off the API key service, refer to API key service setting documentation.

## Required authorization

* Cluster privileges: `manage_own_api_key`

[About API key service settings](https://www.elastic.co/docs/reference/elasticsearch/configuration-reference/security-settings#api-key-service-settings)

## Query String Parameters

- `refresh` (enum Refresh)
  If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes.
  Values: `true`, `false`, `wait_for`

## Request Body

`application/json`

- `expiration` (string Duration) — optional
  The expiration time for the API key.
By default, API keys never expire.
- `name` (string Name) — optional
  A name for the API key.
- `role_descriptors` (map string to RoleDescriptor) — optional
  An array of role descriptors for this API key.
When it is not specified or it is an empty array, the API key will have a point in time snapshot of permissions of the authenticated user.
If you supply role descriptors, the resultant permissions are an intersection of API keys permissions and the authenticated user's permissions thereby limiting the access scope for API keys.
The structure of role descriptor is the same as the request for the create role API.
For more details, refer to the create or update roles API.

NOTE: Due to the way in which this permission intersection is calculated, it is not possible to create an API key that is a child of another API key, unless the derived key is created without any privileges.
In this case, you must explicitly specify a role descriptor with no privileges.
The derived API key can be used for authentication; it will not have authority to call Elasticsearch APIs.
  Map values ({} RoleDescriptor)
  - `cluster` ([] union ClusterPrivilege) — optional
    A list of cluster privileges. These privileges define the cluster level actions that API keys are able to execute.
    Values: `all`, `cancel_task`, `manage`, `manage_api_key`, `manage_behavioral_analytics`, `manage_enrich`, `manage_esql`, `manage_index_templates`, `manage_inference`, `manage_ingest_pipelines`, `manage_logstash_pipelines`, `manage_ml`, `manage_own_api_key`, `manage_pipeline`, `manage_reindex`, `manage_search_application`, `manage_search_query_rules`, `manage_search_synonyms`, `manage_security`, `manage_transform`, `monitor`, `monitor_enrich`, `monitor_esql`, `monitor_inference`, `monitor_ml`, `monitor_reindex`, `monitor_transform`, `none`, `post_behavioral_analytics_event`, `read_pipeline`, `read_security`, `read_project_routing`, `manage_project_routing`
  - `indices` ([] IndicesPrivileges) — optional
    A list of indices permissions entries.
    - `field_security` ({} FieldSecurity) — optional
      The document fields that the owners of the role have read access to.
      - `except` (string Fields) — optional
      - `grant` (string Fields) — optional
    - `names` (union IndexName | [] IndexName) — required
      A list of indices (or index name patterns) to which the permissions in this entry apply.
    - `privileges` ([] union IndexPrivilege) — required
      The index level privileges that owners of the role have on the specified indices.
      Values: `all`, `auto_configure`, `create`, `create_doc`, `create_index`, `create_view`, `delete`, `delete_index`, `delete_view`, `index`, `maintenance`, `manage`, `manage_data_stream_lifecycle`, `manage_view`, `monitor`, `none`, `read`, `read_view_metadata`, `view_index_metadata`, `write`
    - `query` (IndicesPrivilegesQuery) — optional
      A search query that defines the documents the owners of the role have access to. A document within the specified indices must match this query for it to be accessible by the owners of the role.
  - `applications` ([] ApplicationPrivileges) — optional
    A list of application privilege entries
    - `application` (string) — required
      The name of the application to which this entry applies.
    - `privileges` ([] string) — required
      A list of strings, where each element is the name of an application privilege or action.
    - `resources` ([] string) — required
      A list resources to which the privileges are applied.
  - `metadata` (Metadata) — optional
    Optional meta-data. Within the metadata object, keys that begin with `_` are reserved for system usage.
  - `run_as` ([] string) — optional
    A list of users that the API keys can impersonate.
NOTE: In Elastic Cloud Serverless, the run-as feature is disabled.
For API compatibility, you can still specify an empty `run_as` field, but a non-empty list will be rejected.
  - `description` (string) — optional
    Optional description of the role descriptor
  - `restriction` ({} Restriction) — optional
    Restriction for when the role descriptor is allowed to be effective.
    - `workflows` ([] union RestrictionWorkflow) — required
      A list of workflows to which the API key is restricted.
NOTE: In order to use a role restriction, an API key must be created with a single role descriptor.
      Values: `search_application_query`
  - `transient_metadata` (map string to object) — optional
- `metadata` (Metadata) — optional
  Arbitrary metadata that you want to associate with the API key. It supports nested data structure. Within the metadata object, keys beginning with `_` are reserved for system usage.

## Response

`application/json`

- `api_key` (string)
  Generated API key.
- `expiration` (number)
  Expiration in milliseconds for the API key.
- `id` (string Id)
  Unique ID for this API key.
- `name` (string Name)
  Specifies the name for this API key.
- `encoded` (string)
  API key credentials which is the base64-encoding of
the UTF-8 representation of `id` and `api_key` joined
by a colon (`:`).
## Code Examples

#### Console

```console
POST /_security/api_key
{
  "name": "my-api-key",
  "expiration": "1d",   
  "role_descriptors": { 
    "role-a": {
      "cluster": ["all"],
      "indices": [
        {
          "names": ["index-a*"],
          "privileges": ["read"]
        }
      ]
    },
    "role-b": {
      "cluster": ["all"],
      "indices": [
        {
          "names": ["index-b*"],
          "privileges": ["all"]
        }
      ]
    }
  },
  "metadata": {
    "application": "my-application",
    "environment": {
      "level": 1,
      "trusted": true,
      "tags": ["dev", "staging"]
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.security.createApiKey({
  name: "my-api-key",
  expiration: "1d",
  role_descriptors: {
    "role-a": {
      cluster: ["all"],
      indices: [
        {
          names: ["index-a*"],
          privileges: ["read"],
        },
      ],
    },
    "role-b": {
      cluster: ["all"],
      indices: [
        {
          names: ["index-b*"],
          privileges: ["all"],
        },
      ],
    },
  },
  metadata: {
    application: "my-application",
    environment: {
      level: 1,
      trusted: true,
      tags: ["dev", "staging"],
    },
  },
});
```

#### Python

```python
resp = client.security.create_api_key(
    name="my-api-key",
    expiration="1d",
    role_descriptors={
        "role-a": {
            "cluster": [
                "all"
            ],
            "indices": [
                {
                    "names": [
                        "index-a*"
                    ],
                    "privileges": [
                        "read"
                    ]
                }
            ]
        },
        "role-b": {
            "cluster": [
                "all"
            ],
            "indices": [
                {
                    "names": [
                        "index-b*"
                    ],
                    "privileges": [
                        "all"
                    ]
                }
            ]
        }
    },
    metadata={
        "application": "my-application",
        "environment": {
            "level": 1,
            "trusted": True,
            "tags": [
                "dev",
                "staging"
            ]
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_security/api_key" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-api-key",
    "expiration": "1d",
    "role_descriptors": {
      "role-a": {
        "cluster": [
          "all"
        ],
        "indices": [
          {
            "names": [
              "index-a*"
            ],
            "privileges": [
              "read"
            ]
          }
        ]
      },
      "role-b": {
        "cluster": [
          "all"
        ],
        "indices": [
          {
            "names": [
              "index-b*"
            ],
            "privileges": [
              "all"
            ]
          }
        ]
      }
    },
    "metadata": {
      "application": "my-application",
      "environment": {
        "level": 1,
        "trusted": true,
        "tags": [
          "dev",
          "staging"
        ]
      }
    }
  }'
```

#### Java

```java
client.security().createApiKey(c -> c
    .expiration(e -> e
        .time("1d")
    )
    .metadata(Map.of("environment", JsonData.fromJson("""
{"level":1,"trusted":true,"tags":["dev","staging"]}
"""),"application", JsonData.fromJson("\"my-application\"")))
    .name("my-api-key")
    .roleDescriptors(Map.of("role-b", RoleDescriptor.roleDescriptorOf(r -> r
            .cluster("all")
            .indices(i -> i
                .names("index-b*")
                .privileges("all")
            )
        ),"role-a", RoleDescriptor.roleDescriptorOf(r -> r
            .cluster("all")
            .indices(i -> i
                .names("index-a*")
                .privileges("read")
            )
        )))
);
```

#### C#

```c#
var response = await client.Security
    .CreateApiKeyAsync(d1 => d1
        .Expiration("1d")
        .Metadata(new Dictionary<string, object>()
        {
            { "application", "my-application" },
            { "environment", JsonSerializer.Deserialize<JsonElement>("""
            {
              "level": 1,
              "trusted": true,
              "tags": [
                "dev",
                "staging"
              ]
            }
            """) }
        })
        .Name("my-api-key")
        .RoleDescriptors(d2 => d2
            .Add("role-a", d3 => d3
                .Cluster(ClusterPrivilege.All)
                .Indices(d4 => d4
                    .Names(["index-a*"])
                    .Privileges(IndexPrivilege.Read)
                )
            )
            .Add("role-b", d3 => d3
                .Cluster(ClusterPrivilege.All)
                .Indices(d4 => d4
                    .Names(["index-b*"])
                    .Privileges(IndexPrivilege.All)
                )
            )
        )
    );
```

#### PHP

```php
$resp = $client->security()->createApiKey([
    "body" => [
        "name" => "my-api-key",
        "expiration" => "1d",
        "role_descriptors" => [
            "role-a" => [
                "cluster" => array(
                    "all",
                ),
                "indices" => array(
                    [
                        "names" => array(
                            "index-a*",
                        ),
                        "privileges" => array(
                            "read",
                        ),
                    ],
                ),
            ],
            "role-b" => [
                "cluster" => array(
                    "all",
                ),
                "indices" => array(
                    [
                        "names" => array(
                            "index-b*",
                        ),
                        "privileges" => array(
                            "all",
                        ),
                    ],
                ),
            ],
        ],
        "metadata" => [
            "application" => "my-application",
            "environment" => [
                "level" => 1,
                "trusted" => true,
                "tags" => array(
                    "dev",
                    "staging",
                ),
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.security.create_api_key(
  body: {
    "name": "my-api-key",
    "expiration": "1d",
    "role_descriptors": {
      "role-a": {
        "cluster": [
          "all"
        ],
        "indices": [
          {
            "names": [
              "index-a*"
            ],
            "privileges": [
              "read"
            ]
          }
        ]
      },
      "role-b": {
        "cluster": [
          "all"
        ],
        "indices": [
          {
            "names": [
              "index-b*"
            ],
            "privileges": [
              "all"
            ]
          }
        ]
      }
    },
    "metadata": {
      "application": "my-application",
      "environment": {
        "level": 1,
        "trusted": true,
        "tags": [
          "dev",
          "staging"
        ]
      }
    }
  }
)
```

## Response Examples

#### Security create api key response example1

A successful response from `POST /_security/api_key`.

```json
{
  "id": "VuaCfGcBCdbkQm-e5aOx",        
  "name": "my-api-key",
  "expiration": 1544068612110,         
  "api_key": "ui2lp2axTNmsyakw9tvNnw", 
  "encoded": "VnVhQ2ZHY0JDZGJrUW0tZTVhT3g6dWkybHAyYXhUTm1zeWFrdzl0dk5udw=="  
}
```

