---
type: api
title: Find API keys with a query
description: **All methods and paths for this operation:**
url: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/operation/operation-security-query-api-keys
resource: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/operation/operation-security-query-api-keys
products:
  - Elasticsearch
---

# Find API keys with a query


Availability: 7.15+

## Paths

- `POST` (also `GET`) `/_security/_query/api_key`

- [Api key auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#apikeyauth)
- [Basic auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#basicauth)
- [Bearer auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#bearerauth)

## Description

Get a paginated list of API keys and their information.
You can optionally filter the results with a query.

To use this API, you must have at least the `manage_own_api_key` or the `read_security` cluster privileges.
If you have only the `manage_own_api_key` privilege, this API returns only the API keys that you own.
If you have the `read_security`, `manage_api_key`, or greater privileges (including `manage_security`), this API returns all API keys regardless of ownership.
Refer to the linked documentation for examples of how to find API keys:

## Required authorization

* Cluster privileges: `manage_own_api_key`,`read_security`

[About query API key information](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/query-api-keys)

## Query String Parameters

- `with_limited_by` (boolean · default: false)
  Return the snapshot of the owner user's role descriptors associated with the API key.
An API key's actual permission is the intersection of its assigned role descriptors and the owner user's role descriptors (effectively limited by it).
An API key cannot retrieve any API key’s limited-by role descriptors (including itself) unless it has `manage_api_key` or higher privileges.
- `with_profile_uid` (boolean · default: false)
  Determines whether to also retrieve the profile UID for the API key owner principal.
If it exists, the profile UID is returned under the `profile_uid` response field for each API key.
- `typed_keys` (boolean · default: false)
  Determines whether aggregation names are prefixed by their respective types in the response.

## Request Body

`application/json`

- `aggregations` (map string to ApiKeyAggregationContainer) — optional
  Any aggregations to run over the corpus of returned API keys.
Aggregations and queries work together. Aggregations are computed only on the API keys that match the query.
This supports only a subset of aggregation types, namely: `terms`, `range`, `date_range`, `missing`,
`cardinality`, `value_count`, `composite`, `filter`, and `filters`.
Additionally, aggregations only run over the same subset of fields that query works with.
  Map values ({} ApiKeyAggregationContainer)
  - `aggregations` (map string to ApiKeyAggregationContainer) — optional — recursive
    Sub-aggregations for this aggregation.
Only applies to bucket aggregations.
  - `meta` (Metadata) — optional
  - `cardinality` ({} CardinalityAggregation) — optional
    A single-value metrics aggregation that calculates an approximate count of distinct values.
    - `field` (string Field) — optional
      The field on which to run the aggregation.
    - `missing` (boolean | number | string) — optional
      The value to apply to documents that do not have a value.
By default, documents without a value are ignored.
    - `script` (string Script) — optional
    - `precision_threshold` (number · default: 3000) — optional
      A unique count below which counts are expected to be close to accurate.
This allows to trade memory for accuracy.
    - `rehash` (boolean) — optional
    - `execution_hint` (enum CardinalityExecutionMode) — optional
      Mechanism by which cardinality aggregations is run.

Supported values include:
  - `global_ordinals`: Run the aggregation by using global ordinals of the field and resolving those values after finishing a shard.
  - `segment_ordinals`: Run the aggregation by using segment ordinal values and resolving those values after each segment.
  - `direct`: Run the aggregation by using field values directly.
  - `save_memory_heuristic`: Heuristic-based mode, default in Elasticsearch 8.3 and earlier.
  - `save_time_heuristic`: Heuristic-based mode, default in Elasticsearch 8.4 and later.
      Values: `global_ordinals`, `segment_ordinals`, `direct`, `save_memory_heuristic`, `save_time_heuristic`
  - `composite` ({} CompositeAggregation) — optional
    A multi-bucket aggregation that creates composite buckets from different sources.
Unlike the other multi-bucket aggregations, you can use the `composite` aggregation to paginate *all* buckets from a multi-level aggregation efficiently.
    - `after` (CompositeAggregateKey) — optional
      When paginating, use the `after_key` value returned in the previous response to retrieve the next page.
    - `size` (number · default: 10) — optional
      The number of composite buckets that should be returned.
    - `sources` ([] string to CompositeAggregationSource) — optional
      The value sources used to build composite buckets.
Keys are returned in the order of the `sources` definition.
  - `date_range` ({} DateRangeAggregation) — optional
    A multi-bucket value source based aggregation that enables the user to define a set of date ranges - each representing a bucket.
    - `field` (string Field) — optional
      The date field whose values are use to build ranges.
    - `format` (string) — optional
      The date format used to format `from` and `to` in the response.
    - `missing` (boolean | number | string) — optional
      The value to apply to documents that do not have a value.
By default, documents without a value are ignored.
    - `ranges` ([] DateRangeExpression) — optional
      Array of date ranges.
      - `from` (FieldDateMath) — optional
        Start of the range (inclusive).
      - `key` (string) — optional
        Custom key to return the range with.
      - `to` (FieldDateMath) — optional
        End of the range (exclusive).
    - `time_zone` (string) — optional
      Time zone used to convert dates from another time zone to UTC.
    - `keyed` (boolean) — optional
      Set to `true` to associate a unique string key with each bucket and returns the ranges as a hash rather than an array.
  - `filter` ({} ApiKeyQueryContainer) — optional
    A single bucket aggregation that narrows the set of documents to those that match a query.
    - `bool` ({} BoolQuery) — optional
      Matches documents matching boolean combinations of other queries.
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
      - `filter` (union oneOf) — optional
        The clause (query) must appear in matching documents.
However, unlike `must`, the score of the query will be ignored.
        One of: [`QueryContainer[]`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer) or [`QueryContainer`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
        See [QueryContainer](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
      - `minimum_should_match` (number | string MinimumShouldMatch) — optional
        Specifies the number or percentage of `should` clauses returned documents must match.
      - `must` (union oneOf) — optional
        The clause (query) must appear in matching documents and will contribute to the score.
        One of: [`QueryContainer[]`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer) or [`QueryContainer`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
        See [QueryContainer](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
      - `must_not` (union oneOf) — optional
        The clause (query) must not appear in the matching documents.
Because scoring is ignored, a score of `0` is returned for all documents.
        One of: [`QueryContainer[]`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer) or [`QueryContainer`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
        See [QueryContainer](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
      - `should` (union oneOf) — optional
        The clause (query) should appear in the matching document.
        One of: [`QueryContainer[]`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer) or [`QueryContainer`](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
        See [QueryContainer](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
    - `exists` ({} ExistsQuery) — optional
      Returns documents that contain an indexed value for a field.
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
      - `field` (string Field) — required
        Name of the field you wish to search.
    - `ids` ({} IdsQuery) — optional
      Returns documents based on their IDs.
This query uses document IDs stored in the `_id` field.
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
      - `values` (string Ids) — optional
        An array of document IDs.
    - `match` (map string to MatchQuery) — optional
      Returns documents that match a provided text, number, date or boolean value.
The provided text is analyzed before matching.
      Map values ({} MatchQuery)
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
      - `analyzer` (string) — optional
        Analyzer used to convert the text in the query value into tokens.
      - `auto_generate_synonyms_phrase_query` (boolean · default: true) — optional
        If `true`, match phrase queries are automatically created for multi-term synonyms.
      - `cutoff_frequency` (number) — optional — deprecated
      - `fuzziness` (number | string Fuzziness) — optional
        Maximum edit distance allowed for matching.
      - `fuzzy_rewrite` (string) — optional
        Method used to rewrite the query.
      - `fuzzy_transpositions` (boolean · default: true) — optional
        If `true`, edits for fuzzy matching include transpositions of two adjacent characters (for example, `ab` to `ba`).
      - `lenient` (boolean · default: false) — optional
        If `true`, format-based errors, such as providing a text query value for a numeric field, are ignored.
      - `max_expansions` (number · default: 50) — optional
        Maximum number of terms to which the query will expand.
      - `minimum_should_match` (number | string MinimumShouldMatch) — optional
        Minimum number of clauses that must match for a document to be returned.
      - `operator` (enum Operator · default: 'or') — optional
        Boolean logic used to interpret text in the query value.
        Values: `and`, `AND`, `or`, `OR`
      - `prefix_length` (number · default: 0) — optional
        Number of beginning characters left unchanged for fuzzy matching.
      - `query` (boolean | number | string) — required
        Text, number, boolean value or date you wish to find in the provided field.
      - `zero_terms_query` (enum ZeroTermsQuery · default: 'none') — optional
        Indicates whether no documents are returned if the `analyzer` removes all tokens, such as when using a `stop` filter.

Supported values include:
  - `all`: Returns all documents, similar to a `match_all` query.
  - `none`: No documents are returned if the `analyzer` removes all tokens.
        Values: `all`, `none`
    - `match_all` ({} MatchAllQuery) — optional
      Matches all documents, giving them all a `_score` of 1.0.
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
    - `prefix` (map string to PrefixQuery) — optional
      Returns documents that contain a specific prefix in a provided field.
      Map values ({} PrefixQuery)
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
      - `rewrite` (string) — optional
        Method used to rewrite the query.
      - `value` (string) — required
        Beginning characters of terms you wish to find in the provided field.
      - `case_insensitive` (boolean · default: false) — optional
        Allows ASCII case insensitive matching of the value with the indexed field values when set to `true`.
Default is `false` which means the case sensitivity of matching depends on the underlying field’s mapping.
    - `range` (map string to RangeQuery) — optional
      Returns documents that contain terms within a provided range.
    - `simple_query_string` ({} SimpleQueryStringQuery) — optional
      Returns documents based on a provided query string, using a parser with a limited but fault-tolerant syntax.
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
      - `analyzer` (string) — optional
        Analyzer used to convert text in the query string into tokens.
      - `analyze_wildcard` (boolean · default: false) — optional
        If `true`, the query attempts to analyze wildcard terms in the query string.
      - `auto_generate_synonyms_phrase_query` (boolean · default: true) — optional
        If `true`, the parser creates a match_phrase query for each multi-position token.
      - `default_operator` (enum Operator · default: 'or') — optional
        Default boolean logic used to interpret text in the query string if no operators are specified.
        Values: `and`, `AND`, `or`, `OR`
      - `fields` ([] string Field) — optional
        Array of fields you wish to search.
Accepts wildcard expressions.
You also can boost relevance scores for matches to particular fields using a caret (`^`) notation.
Defaults to the `index.query.default_field index` setting, which has a default value of `*`.
      - `flags` (SimpleQueryStringFlags · default: ALL) — optional
        List of enabled operators for the simple query string syntax.
        Values: `NONE`, `AND`, `NOT`, `OR`, `PREFIX`, `PHRASE`, `PRECEDENCE`, `ESCAPE`, `WHITESPACE`, `FUZZY`, `NEAR`, `SLOP`, `ALL`
      - `fuzzy_max_expansions` (number · default: 50) — optional
        Maximum number of terms to which the query expands for fuzzy matching.
      - `fuzzy_prefix_length` (number · default: 0) — optional
        Number of beginning characters left unchanged for fuzzy matching.
      - `fuzzy_transpositions` (boolean) — optional
        If `true`, edits for fuzzy matching include transpositions of two adjacent characters (for example, `ab` to `ba`).
      - `lenient` (boolean · default: false) — optional
        If `true`, format-based errors, such as providing a text value for a numeric field, are ignored.
      - `minimum_should_match` (number | string MinimumShouldMatch) — optional
        Minimum number of clauses that must match for a document to be returned.
      - `query` (string) — required
        Query string in the simple query string syntax you wish to parse and use for search.
      - `quote_field_suffix` (string) — optional
        Suffix appended to quoted text in the query string.
    - `term` (map string to TermQuery) — optional
      Returns documents that contain an exact term in a provided field.
To return a document, the query term must exactly match the queried field's value, including whitespace and capitalization.
      Map values ({} TermQuery)
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
      - `value` (FieldValue) — required
        Term you wish to find in the provided field.
      - `case_insensitive` (boolean · default: false) — optional
        Allows ASCII case insensitive matching of the value with the indexed field values when set to `true`.
When `false`, the case sensitivity of matching depends on the underlying field’s mapping.
    - `terms` ({} TermsQuery) — optional
      Returns documents that contain one or more exact terms in a provided field.
To return a document, one or more terms must exactly match a field value, including whitespace and capitalization.
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
    - `wildcard` (map string to WildcardQuery) — optional
      Returns documents that contain terms matching a wildcard pattern.
      Map values ({} WildcardQuery)
      - `boost` (number · default: 1) — optional
        Floating point number used to decrease or increase the relevance scores of the query.
Boost values are relative to the default value of 1.0.
A boost value between 0 and 1.0 decreases the relevance score.
A value greater than 1.0 increases the relevance score.
      - `_name` (string) — optional
      - `case_insensitive` (boolean) — optional
        Allows case insensitive matching of the pattern with the indexed field values when set to true. Default is false which means the case sensitivity of matching depends on the underlying field’s mapping.
      - `rewrite` (string) — optional
        Method used to rewrite the query.
      - `value` (string) — optional
        Wildcard pattern for terms you wish to find in the provided field. Required, when wildcard is not set.
      - `wildcard` (string) — optional
        Wildcard pattern for terms you wish to find in the provided field. Required, when value is not set.
  - `filters` ({} ApiKeyFiltersAggregation) — optional
    A multi-bucket aggregation where each bucket contains the documents that match a query.
    - `filters` (BucketsApiKeyQueryContainer) — optional
      Collection of queries from which to build buckets.
    - `other_bucket` (boolean) — optional
      Set to `true` to add a bucket to the response which will contain all documents that do not match any of the given filters.
    - `other_bucket_key` (string · default: _other_) — optional
      The key with which the other bucket is returned.
    - `keyed` (boolean · default: true) — optional
      By default, the named filters aggregation returns the buckets as an object.
Set to `false` to return the buckets as an array of objects.
  - `missing` ({} MissingAggregation) — optional
    - `field` (string Field) — optional
      The name of the field.
    - `missing` (boolean | number | string) — optional
  - `range` ({} RangeAggregation) — optional
    A multi-bucket value source based aggregation that enables the user to define a set of ranges - each representing a bucket.
    - `field` (string Field) — optional
      The date field whose values are use to build ranges.
    - `missing` (number) — optional
      The value to apply to documents that do not have a value.
By default, documents without a value are ignored.
    - `ranges` ([] AggregationRange) — optional
      An array of ranges used to bucket documents.
      - `from` (union number | string) — optional — nullable
        Start of the range (inclusive).
      - `key` (string) — optional
        Custom key to return the range with.
      - `to` (union number | string) — optional — nullable
        End of the range (exclusive).
    - `script` (string Script) — optional
    - `keyed` (boolean) — optional
      Set to `true` to associate a unique string key with each bucket and return the ranges as a hash rather than an array.
    - `format` (string) — optional
  - `terms` ({} TermsAggregation) — optional
    A multi-bucket value source based aggregation where buckets are dynamically built - one per unique value.
    - `collect_mode` (enum TermsAggregationCollectMode) — optional
      Determines how child aggregations should be calculated: breadth-first or depth-first.

Supported values include:
  - `depth_first`: Expands all branches of the aggregation tree in one depth-first pass, before any pruning occurs.
  - `breadth_first`: Caches the set of documents that fall into the uppermost buckets for subsequent replay.
      Values: `depth_first`, `breadth_first`
    - `exclude` (TermsExclude) — optional
      Values to exclude.
Accepts regular expressions and partitions.
    - `execution_hint` (enum TermsAggregationExecutionHint) — optional
      Determines whether the aggregation will use field values directly or global ordinals.
      Values: `map`, `global_ordinals`, `global_ordinals_hash`, `global_ordinals_low_cardinality`
    - `field` (string Field) — optional
      The field from which to return terms.
    - `include` (TermsInclude) — optional
      Values to include.
Accepts regular expressions and partitions.
    - `min_doc_count` (number · default: 1) — optional
      Only return values that are found in more than `min_doc_count` hits.
    - `missing` (boolean | number | string) — optional
      The value to apply to documents that do not have a value.
By default, documents without a value are ignored.
    - `missing_order` (enum MissingOrder) — optional
      Values: `first`, `last`, `default`
    - `missing_bucket` (boolean) — optional
    - `value_type` (string) — optional
      Coerced unmapped fields into the specified type.
    - `order` (AggregateOrder) — optional
      Specifies the sort order of the buckets.
Defaults to sorting by descending document count.
    - `script` (string Script) — optional
    - `shard_min_doc_count` (number) — optional
      Regulates the certainty a shard has if the term should actually be added to the candidate list or not with respect to the `min_doc_count`.
Terms will only be considered if their local shard frequency within the set is higher than the `shard_min_doc_count`.
    - `shard_size` (number) — optional
      The number of candidate terms produced by each shard.
By default, `shard_size` will be automatically estimated based on the number of shards and the `size` parameter.
    - `show_term_doc_count_error` (boolean) — optional
      Set to `true` to return the `doc_count_error_upper_bound`, which is an upper bound to the error on the `doc_count` returned by each shard.
    - `size` (number · default: 10) — optional
      The number of buckets returned out of the overall terms list.
    - `format` (string) — optional
  - `value_count` ({} ValueCountAggregation) — optional
    A single-value metrics aggregation that counts the number of values that are extracted from the aggregated documents.
    - `field` (string Field) — optional
      The field on which to run the aggregation.
    - `missing` (boolean | number | string) — optional
      The value to apply to documents that do not have a value.
By default, documents without a value are ignored.
    - `script` (string Script) — optional
    - `format` (string) — optional
- `query` ({} ApiKeyQueryContainer) — optional
  A query to filter which API keys to return.
If the query parameter is missing, it is equivalent to a `match_all` query.
The query supports a subset of query types, including `match_all`, `bool`, `term`, `terms`, `match`,
`ids`, `prefix`, `wildcard`, `exists`, `range`, and `simple_query_string`.
You can query the following public information associated with an API key: `id`, `type`, `name`,
`creation`, `expiration`, `invalidated`, `invalidation`, `username`, `realm`, and `metadata`.

NOTE: The queryable string values associated with API keys are internally mapped as keywords.
Consequently, if no `analyzer` parameter is specified for a `match` query, then the provided match query string is interpreted as a single keyword value.
Such a match query is hence equivalent to a `term` query.
  Same fields as `filter` in `aggregations`
- `from` (number · default: 0) — optional
  The starting document offset.
It must not be negative.
By default, you cannot page through more than 10,000 hits using the `from` and `size` parameters.
To page through more hits, use the `search_after` parameter.
- `sort` (Sort) — optional
  The sort definition.
Other than `id`, all public fields of an API key are eligible for sorting.
In addition, sort can also be applied to the `_doc` field to sort by index order.
- `size` (number · default: 10) — optional
  The number of hits to return.
It must not be negative.
The `size` parameter can be set to `0`, in which case no API key matches are returned, only the aggregation results.
By default, you cannot page through more than 10,000 hits using the `from` and `size` parameters.
To page through more hits, use the `search_after` parameter.
- `search_after` (SortResults) — optional
  The search after definition.

## Response

`application/json`

- `total` (number)
  The total number of API keys found.
- `count` (number)
  The number of API keys returned in the response.
- `api_keys` ([] ApiKey)
  A list of API key information.
  - `id` (string Id)
    Id for the API key
  - `name` (string Name)
    Name of the API key.
  - `type` (enum ApiKeyType)
    The type of the API key (e.g. `rest` or `cross_cluster`).
    Values: `rest`, `cross_cluster`
  - `creation` (EpochTimeUnitMillis)
    Creation time for the API key in milliseconds.
  - `expiration` (EpochTimeUnitMillis)
    Expiration time for the API key in milliseconds.
  - `invalidated` (boolean)
    Invalidation status for the API key.
If the key has been invalidated, it has a value of `true`. Otherwise, it is `false`.
  - `invalidation` (EpochTimeUnitMillis)
    If the key has been invalidated, invalidation time in milliseconds.
  - `username` (string)
    Principal for which this API key was created
  - `realm` (string)
    Realm name of the principal for which this API key was created.
  - `realm_type` (string)
    Realm type of the principal for which this API key was created
  - `metadata` (Metadata)
    Metadata of the API key
  - `role_descriptors` (map string to RoleDescriptor)
    The role descriptors assigned to this API key when it was created or last updated.
An empty role descriptor means the API key inherits the owner user’s permissions.
    Map values ({} RoleDescriptor)
    - `cluster` ([] union ClusterPrivilege)
      A list of cluster privileges. These privileges define the cluster level actions that API keys are able to execute.
      Values: `all`, `cancel_task`, `clone_api_key`, `create_snapshot`, `cross_cluster_replication`, `cross_cluster_search`, `delegate_pki`, `grant_api_key`, `manage`, `manage_api_key`, `manage_autoscaling`, `manage_behavioral_analytics`, `manage_ccr`, `manage_data_frame_transforms`, `manage_data_stream_global_retention`, `manage_enrich`, `manage_esql`, `manage_ilm`, `manage_index_templates`, `manage_inference`, `manage_ingest_pipelines`, `manage_logstash_pipelines`, `manage_ml`, `manage_oidc`, `manage_own_api_key`, `manage_pipeline`, `manage_reindex`, `manage_rollup`, `manage_saml`, `manage_search_application`, `manage_search_query_rules`, `manage_search_synonyms`, `manage_security`, `manage_service_account`, `manage_slm`, `manage_token`, `manage_transform`, `manage_user_profile`, `manage_watcher`, `monitor`, `monitor_data_frame_transforms`, `monitor_data_stream_global_retention`, `monitor_enrich`, `monitor_esql`, `monitor_inference`, `monitor_ml`, `monitor_reindex`, `monitor_rollup`, `monitor_snapshot`, `monitor_stats`, `monitor_text_structure`, `monitor_transform`, `monitor_watcher`, `none`, `post_behavioral_analytics_event`, `read_ccr`, `read_fleet_secrets`, `read_ilm`, `read_pipeline`, `read_security`, `read_slm`, `transport_client`, `write_connector_secrets`, `write_fleet_secrets`
    - `indices` ([] IndicesPrivileges)
      A list of indices permissions entries.
      - `field_security` ({} FieldSecurity)
        The document fields that the owners of the role have read access to.
        - `except` (string Fields)
        - `grant` (string Fields)
      - `names` (union IndexName | [] IndexName)
        A list of indices (or index name patterns) to which the permissions in this entry apply.
      - `privileges` ([] union IndexPrivilege)
        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`, `cross_cluster_replication`, `cross_cluster_replication_internal`, `delete`, `delete_index`, `delete_view`, `index`, `maintenance`, `manage`, `manage_data_stream_lifecycle`, `manage_follow_index`, `manage_ilm`, `manage_leader_index`, `manage_view`, `monitor`, `none`, `read`, `read_cross_cluster`, `read_view_metadata`, `view_index_metadata`, `write`
      - `query` (IndicesPrivilegesQuery)
        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.
      - `allow_restricted_indices` (boolean · default: false)
        Set to `true` if using wildcard or regular expressions for patterns that cover restricted indices. Implicitly, restricted indices have limited privileges that can cause pattern tests to fail. If restricted indices are explicitly included in the `names` list, Elasticsearch checks privileges against these indices regardless of the value set for `allow_restricted_indices`.
    - `remote_indices` ([] RemoteIndicesPrivileges)
      A list of indices permissions for remote clusters.
      - `clusters` (string Names)
        A list of cluster aliases to which the permissions in this entry apply.
      - `field_security` ({} FieldSecurity)
        The document fields that the owners of the role have read access to.
        - `except` (string Fields)
        - `grant` (string Fields)
      - `names` (union IndexName | [] IndexName)
        A list of indices (or index name patterns) to which the permissions in this entry apply.
      - `privileges` ([] union IndexPrivilege)
        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`, `cross_cluster_replication`, `cross_cluster_replication_internal`, `delete`, `delete_index`, `delete_view`, `index`, `maintenance`, `manage`, `manage_data_stream_lifecycle`, `manage_follow_index`, `manage_ilm`, `manage_leader_index`, `manage_view`, `monitor`, `none`, `read`, `read_cross_cluster`, `read_view_metadata`, `view_index_metadata`, `write`
      - `query` (IndicesPrivilegesQuery)
        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.
      - `allow_restricted_indices` (boolean · default: false)
        Set to `true` if using wildcard or regular expressions for patterns that cover restricted indices. Implicitly, restricted indices have limited privileges that can cause pattern tests to fail. If restricted indices are explicitly included in the `names` list, Elasticsearch checks privileges against these indices regardless of the value set for `allow_restricted_indices`.
    - `remote_cluster` ([] RemoteClusterPrivileges)
      A list of cluster permissions for remote clusters.
NOTE: This is limited a subset of the cluster permissions.
      - `clusters` (string Names)
        A list of cluster aliases to which the permissions in this entry apply.
      - `privileges` ([] enum RemoteClusterPrivilege)
        The cluster level privileges that owners of the role have on the remote cluster.
        Values: `monitor_enrich`, `monitor_stats`
    - `global` ({} GlobalPrivilege)
      An object defining global privileges. A global privilege is a form of cluster privilege that is request-aware.
      - `application` ({} ApplicationGlobalUserPrivileges)
        - `manage` ({} ManageUserPrivileges)
          - `applications` ([] string)
      - `data_source` ([] DataSourcePrivileges)
        A list of data source privilege entries, used to grant access to ES|QL data sources.
        - `names` ([] string)
          A list of data source names or wildcard patterns to which the permissions in this entry apply.
        - `privileges` ([] union DataSourcePrivilege)
          The data source privileges that owners of the role have for the specified data sources.

Supported values include:
  - `create`: Grants privilege to create a data source with a matching name.
  - `delete`: Grants privilege to delete a data source with a matching name.
  - `read_metadata`: Grants privilege to read a data source's metadata.
  - `read`: Grants privilege to attach a dataset to a data source with a matching name.
  - `manage`: Grants all data source privileges, including `create`, `delete`, `read`, and `read_metadata`.
          Values: `create`, `delete`, `read_metadata`, `read`, `manage`
    - `applications` ([] ApplicationPrivileges)
      A list of application privilege entries
      - `application` (string)
        The name of the application to which this entry applies.
      - `privileges` ([] string)
        A list of strings, where each element is the name of an application privilege or action.
      - `resources` ([] string)
        A list resources to which the privileges are applied.
    - `metadata` (Metadata)
      Optional meta-data. Within the metadata object, keys that begin with `_` are reserved for system usage.
    - `run_as` ([] string)
      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 description of the role descriptor
    - `restriction` ({} Restriction)
      Restriction for when the role descriptor is allowed to be effective.
      - `workflows` ([] union RestrictionWorkflow)
        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)
  - `limited_by` ([] string to RoleDescriptor)
    The owner user’s permissions associated with the API key.
It is a point-in-time snapshot captured at creation and subsequent updates.
An API key’s effective permissions are an intersection of its assigned privileges and the owner user’s permissions.
  - `access` ({} Access)
    The access granted to cross-cluster API keys.
The access is composed of permissions for cross cluster search and cross cluster replication.
At least one of them must be specified.
When specified, the new access assignment fully replaces the previously assigned access.
    - `replication` ([] ReplicationAccess)
      A list of indices permission entries for cross-cluster replication.
      - `names` (union IndexName | [] IndexName)
        A list of indices (or index name patterns) to which the permissions in this entry apply.
      - `allow_restricted_indices` (boolean · default: false)
        This needs to be set to true if the patterns in the names field should cover system indices.
    - `search` ([] SearchAccess)
      A list of indices permission entries for cross-cluster search.
      - `field_security` ({} FieldSecurity)
        The document fields that the owners of the role have read access to.
        - `except` (string Fields)
        - `grant` (string Fields)
      - `names` (union IndexName | [] IndexName)
        A list of indices (or index name patterns) to which the permissions in this entry apply.
      - `query` (IndicesPrivilegesQuery)
        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.
      - `allow_restricted_indices` (boolean · default: false)
        Set to `true` if using wildcard or regular expressions for patterns that cover restricted indices. Implicitly, restricted indices have limited privileges that can cause pattern tests to fail. If restricted indices are explicitly included in the `names` list, Elasticsearch checks privileges against these indices regardless of the value set for `allow_restricted_indices`.
  - `certificate_identity` (string)
    The certificate identity associated with a cross-cluster API key.
Restricts the API key to connections authenticated by a specific TLS certificate.
Only applicable to cross-cluster API keys.
  - `profile_uid` (string)
    The profile uid for the API key owner principal, if requested and if it exists
  - `_sort` (SortResults)
    Sorting values when using the `sort` parameter with the `security.query_api_keys` API.
- `aggregations` (map string to ApiKeyAggregate)
  The aggregations result, if requested.
## Code Examples

#### Console

```console
POST /_security/_query/api_key?with_limited_by=true
{
  "query": {
    "ids": {
      "values": [
        "VuaCfGcBCdbkQm-e5aOx"
      ]
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.security.queryApiKeys({
  with_limited_by: "true",
  query: {
    ids: {
      values: ["VuaCfGcBCdbkQm-e5aOx"],
    },
  },
});
```

#### Python

```python
resp = client.security.query_api_keys(
    with_limited_by=True,
    query={
        "ids": {
            "values": [
                "VuaCfGcBCdbkQm-e5aOx"
            ]
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_security/_query/api_key?with_limited_by=true" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": {
      "ids": {
        "values": [
          "VuaCfGcBCdbkQm-e5aOx"
        ]
      }
    }
  }'
```

#### Java

```java
client.security().queryApiKeys(q -> q
    .query(qu -> qu
        .ids(i -> i
            .values("VuaCfGcBCdbkQm-e5aOx")
        )
    )
    .withLimitedBy(true)
);
```

#### C#

```c#
var response = await client.Security
    .QueryApiKeysAsync(d1 => d1
        .WithLimitedBy(true)
        .Query(d2 => d2
            .Ids(d3 => d3
                .Values(new[] { "VuaCfGcBCdbkQm-e5aOx" })
            )
        )
    );
```

#### PHP

```php
$resp = $client->security()->queryApiKeys([
    "with_limited_by" => "true",
    "body" => [
        "query" => [
            "ids" => [
                "values" => array(
                    "VuaCfGcBCdbkQm-e5aOx",
                ),
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.security.query_api_keys(
  with_limited_by: "true",
  body: {
    "query": {
      "ids": {
        "values": [
          "VuaCfGcBCdbkQm-e5aOx"
        ]
      }
    }
  }
)
```

## Response Examples

#### Query API keys by ID

A successful response from `GET /_security/_query/api_key?with_limited_by=true`. The `limited_by` details are the owner user's permissions associated with the API key. It is a point-in-time snapshot captured at creation and subsequent updates. An API key's effective permissions are an intersection of its assigned privileges and the owner user's permissions.

```json
{
  "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
            }
          }
        }
      ]
    }
  ]
}
```

#### Query API keys with pagination

An abbreviated response from `GET /_security/_query/api_key` that contains a list of matched API keys along with their sort values. The first sort value is creation time, which is displayed in `date_time` format. The second sort value is the API key name.

```json
{
  "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"
      ]
    }
  ]
}
```

#### Query all API keys

A successful response from `GET /_security/_query/api_key`. It includes the role descriptors that are assigned to each API key when it was created or last updated. Note that an API key's effective permissions are an intersection of its assigned privileges and the point-in-time snapshot of the owner user's permissions. An empty role descriptors object means the API key inherits the owner user's permissions.

```json
{
  "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": { } 
    }
  ]
}
```

