﻿---
title: Query API key information examples
description: The Query API key information API retrieves API key metadata in a paginated fashion. This page shows examples to demonstrate how to retrieve, filter,...
url: https://www.elastic.co/elastic/docs-builder/docs/2771/reference/elasticsearch/rest-apis/query-api-keys
products:
  - Elasticsearch
applies_to:
  - Elastic Stack: Generally available
---

# Query API key information examples
The [Query API key information API](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-query-api-keys) retrieves API key metadata in a paginated fashion. This page shows examples to demonstrate how to retrieve, filter, sort, and aggregate API key data using query DSL and aggregation features.
You can learn how to:
- [Retrieve all API keys](#retrieve-all-api-keys)
- [Group API keys by owner and expiration](#group-api-keys-by-owner-and-expiration)
- [Group invalidated API keys by owner and name](#group-invalidated-api-keys-by-owner-and-name)


## Retrieve all API keys

The following request lists all API keys, assuming you have the `manage_api_key` privilege:
```json
```

A successful call returns a JSON structure that contains the information retrieved from one or more API keys:
```js
{
  "total": 3,
  "count": 3,
  "api_keys": [ 
    {
      "id": "nkvrGXsB8w290t56q3Rg",
      "name": "my-api-key-1",
      "creation": 1628227480421,
      "expiration": 1629091480421,
      "invalidated": false,
      "username": "elastic",
      "realm": "reserved",
      "realm_type": "reserved",
      "metadata": {
        "letter": "a"
      },
      "role_descriptors": { 
        "role-a": {
          "cluster": [
            "monitor"
          ],
          "indices": [
            {
              "names": [
                "index-a"
              ],
              "privileges": [
                "read"
              ],
              "allow_restricted_indices": false
            }
          ],
          "applications": [ ],
          "run_as": [ ],
          "metadata": { },
          "transient_metadata": {
            "enabled": true
          }
        }
      }
    },
    {
      "id": "oEvrGXsB8w290t5683TI",
      "name": "my-api-key-2",
      "creation": 1628227498953,
      "expiration": 1628313898953,
      "invalidated": false,
      "username": "elastic",
      "realm": "reserved",
      "metadata": {
        "letter": "b"
      },
      "role_descriptors": { } 
    }
  ]
}
```

If you create an API key with the following details:
```json

{
  "name": "application-key-1",
  "metadata": { "application": "my-application"}
}
```

A successful call returns a JSON structure that provides API key information. For example:
```json
{
  "id": "VuaCfGcBCdbkQm-e5aOx",
  "name": "application-key-1",
  "api_key": "ui2lp2axTNmsyakw9tvNnw",
  "encoded": "VnVhQ2ZHY0JDZGJrUW0tZTVhT3g6dWkybHAyYXhUTm1zeWFrdzl0dk5udw=="
}
```

Use the information from the response to retrieve the API key by ID:
```json

{
  "query": {
    "ids": {
      "values": [
        "VuaCfGcBCdbkQm-e5aOx"
      ]
    }
  }
}
```

A successful call returns a JSON structure for API key information including its limited-by role descriptors:
```js
{
  "api_keys": [
    {
      "id": "VuaCfGcBCdbkQm-e5aOx",
      "name": "application-key-1",
      "creation": 1548550550158,
      "expiration": 1548551550158,
      "invalidated": false,
      "username": "myuser",
      "realm": "native1",
      "realm_type": "native",
      "metadata": {
        "application": "my-application"
      },
      "role_descriptors": { },
      "limited_by": [ 
        {
          "role-power-user": {
            "cluster": [
              "monitor"
            ],
            "indices": [
              {
                "names": [
                  "*"
                ],
                "privileges": [
                  "read"
                ],
                "allow_restricted_indices": false
              }
            ],
            "applications": [ ],
            "run_as": [ ],
            "metadata": { },
            "transient_metadata": {
              "enabled": true
            }
          }
        }
      ]
    }
  ]
}
```

You can also retrieve the API key by name:
```json

{
  "query": {
    "term": {
      "name": {
        "value": "application-key-1"
      }
    }
  }
}
```

Use a `bool` query to issue complex logical conditions and use `from`, `size`, `sort` to help paginate the result:
```js
GET /_security/_query/api_key
{
  "query": {
    "bool": {
      "must": [
        {
          "prefix": {
            "name": "app1-key-" 
          }
        },
        {
          "term": {
            "invalidated": "false" 
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "name": "app1-key-01" 
          }
        }
      ],
      "filter": [
        {
          "wildcard": {
            "username": "org-*-user" 
          }
        },
        {
          "term": {
            "metadata.environment": "production" 
          }
        }
      ]
    }
  },
  "from": 20, 
  "size": 10, 
  "sort": [ 
    { "creation": { "order": "desc", "format": "date_time" } },
    "name"
  ]
}
```

The response contains a list of matched API keys along with their sort values:
```js
{
  "total": 100,
  "count": 10,
  "api_keys": [
    {
      "id": "CLXgVnsBOGkf8IyjcXU7",
      "name": "app1-key-79",
      "creation": 1629250154811,
      "invalidated": false,
      "username": "org-admin-user",
      "realm": "native1",
      "metadata": {
        "environment": "production"
      },
      "role_descriptors": { },
      "_sort": [
        "2021-08-18T01:29:14.811Z",  
        "app1-key-79"  
      ]
    },
    {
      "id": "BrXgVnsBOGkf8IyjbXVB",
      "name": "app1-key-78",
      "creation": 1629250153794,
      "invalidated": false,
      "username": "org-admin-user",
      "realm": "native1",
      "metadata": {
        "environment": "production"
      },
      "role_descriptors": { },
      "_sort": [
        "2021-08-18T01:29:13.794Z",
        "app1-key-78"
      ]
    },
    ...
  ]
}
```


## Group API keys by owner and expiration

For example, given 2 users "june" and "king", each owning 3 API keys:
- one that never expires (invalidated for user "king")
- one that expires in 10 days
- and one that expires in 100 day (invalidated for user "june")

The following request returns the names of valid (not expired and not invalidated) API keys that expire soon (in 30 days time), grouped by owner username.

### Request

```json

{
  "size": 0,
  "query": {
    "bool": {
      "must": {
        "term": {
          "invalidated": false  <1>
        }
      },
      "should": [  <2>
        {
          "range": { "expiration": { "gte": "now" } }
        },
        {
          "bool": { "must_not": { "exists": { "field": "expiration" } } }
        }
      ],
      "minimum_should_match": 1
    }
  },
  "aggs": {
    "keys_by_username": {
      "composite": {
        "sources": [ { "usernames": { "terms": { "field": "username" } } } ]  <3>
      },
      "aggs": {
        "expires_soon": {
          "filter": {
            "range": { "expiration": { "lte": "now+30d/d" } }  <4>
          },
          "aggs": {
            "key_names": { "terms": { "field": "name" } }
          }
        }
      }
    }
  }
}
```


### Response

```json
{
  "total" : 4,  
  "count" : 0,
  "api_keys" : [ ],
  "aggregations" : {
    "keys_by_username" : {
      "after_key" : {
        "usernames" : "king"
      },
      "buckets" : [
        {
          "key" : {
            "usernames" : "june"
          },
          "doc_count" : 2,  
          "expires_soon" : {
            "doc_count" : 1,
            "key_names" : {
              "doc_count_error_upper_bound" : 0,
              "sum_other_doc_count" : 0,
              "buckets" : [
                {
                  "key" : "june-key-10",
                  "doc_count" : 1
                }
              ]
            }
          }
        },
        {
          "key" : {
            "usernames" : "king"
          },
          "doc_count" : 2,
          "expires_soon" : {
            "doc_count" : 1,  
            "key_names" : {
              "doc_count_error_upper_bound" : 0,
              "sum_other_doc_count" : 0,
              "buckets" : [  
                {
                  "key" : "king-key-10",
                  "doc_count" : 1
                }
              ]
            }
          }
        }
      ]
    }
  }
}
```


## Group invalidated API keys by owner and name

To retrieve the invalidated (but not yet deleted) API keys, grouped by owner username and API key name, issue the following request:

### Request

```json

{
  "size": 0,
  "query": {
    "bool": {
      "filter": {
        "term": {
          "invalidated": true
        }
      }
    }
  },
  "aggs": {
    "invalidated_keys": {
      "composite": {
        "sources": [
          { "username": { "terms": { "field": "username" } } },
          { "key_name": { "terms": { "field": "name" } } }
        ]
      }
    }
  }
}
```


### Response

```json
{
  "total" : 2,
  "count" : 0,
  "api_keys" : [ ],
  "aggregations" : {
    "invalidated_keys" : {
      "after_key" : {
        "username" : "king",
        "key_name" : "king-key-no-expire"
      },
      "buckets" : [
        {
          "key" : {
            "username" : "june",
            "key_name" : "june-key-100"
          },
          "doc_count" : 1
        },
        {
          "key" : {
            "username" : "king",
            "key_name" : "king-key-no-expire"
          },
          "doc_count" : 1
        }
      ]
    }
  }
}
```