> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Update API key

> Replace every permission of an existing API key.

export const Legacy = ({title, href}) => {
  return <Note>

    This page documents an earlier version of the API client.
    For the latest version, see <a href={href}>{title}</a>.

    </Note>;
};

<Legacy title="Update an API key" href="/doc/libraries/sdk/methods/search/update-api-key" />

**Required ACL:** `Admin`

Any unspecified permission field will be reset to its default value.
To ensure that existing permissions aren't lost when applying an update,
make sure to include the existing permissions you don't want to change.

## Examples

### Update the permissions of an existing key

<CodeGroup>
  ```cs C# theme={"system"}
  // Update an existing API key that is valid for 300 seconds
  ApiKey apiKeyToUpdate = new ApiKey
  {
      Value = "YourAPIKey",
      Acl = new List<string> { "search" },
      MaxHitsPerQuery = 0,
      MaxQueriesPerIPPerHour = 0,
      Validity = 300
  };

  var res = client.UpdateApiKey(apiKeyToUpdate);

  // Asynchronous
  var res = await client.UpdateApiKeyAsync(apiKeyToUpdate);

  // Update an existing index-specific API key valid for 300 seconds,
  // with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
  ApiKey apiKeyToUpdate = new ApiKey
  {
      Value = "YourAPIKey",
      Acl = new List<string> { "search" },
      Indexes = new List<string> { "dev_*" },
      MaxHitsPerQuery = 20,
      MaxQueriesPerIPPerHour = 100,
      Validity = 300
  };

  var res = index.UpdateApiKey(apiKeyToUpdate);

  // Asynchronous
  var res = await index.UpdateApiKeyAsync(apiKeyToUpdate);
  ```

  ```go Go theme={"system"}
  // Update an existing index-specific API key valid for 5 minutes, with a rate
  // limit of 100 calls per hour per IP and a maximum of 20 hits
  key := search.Key{
    ACL:                    []string{"search"},
    Indexes:                []string{"dev_*"}
    Validity:               5 * time.Minute,
    MaxQueriesPerIPPerHour: 100,
    MaxHitsPerQuery:        20,
    Value:                  "f420238212c54dcfad07ea0aa6d5c45f",
  }

  res, err := client.UpdateAPIKey(key)
  res.Wait()
  fmt.Println(res.Key)
  ```

  ```java Java theme={"system"}
  // Creates a new API key that is valid for 300 seconds

  ApiKey apiKey = new ApiKey()
      .setValue("YourAPIKey")
      .setAcl(Collections.singletonList("search"))
      .setValidity(300);

  client.updateApiKey(apiKey);

  // Async 
  client.updateApiKeyAsync(apiKey);

  // Update an index-specific API key valid for 300 seconds,
  // with a rate limit of 100 calls per hour per IP and a maximum of 20 hits

  ApiKey apiKey = new ApiKey()
      .setValue("YourAPIKey")
      .setAcl(Arrays.asList("search"))
      .setValidity(300L)
      .setMaxQueriesPerIPPerHour(200)
      .setMaxHitsPerQuery(20);

  client.updateApiKey(apiKey);

  // Async
  client.updateApiKeyAsync(apiKey);
  ```

  ```js JavaScript theme={"system"}
  // Update an existing API key that is valid for 300 seconds
  client.updateApiKey('YourAPIKey', {
    acl: ['search'],
    validity: 300,
  }).then(({ key }) => {
    console.log(key);
  });

  // Update an existing index-specific API key valid for 300 seconds, with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
  client.updateApiKey('YourAPIKey', {
    acl: ['search'],
    validity: 300,
    maxQueriesPerIPPerHour: 100,
    maxHitsPerQuery: 20,
  }).then(({ key }) => {
    console.log(key);
  });
  ```

  ```kotlin Kotlin theme={"system"}
  // Update an existing index-specific API key valid for 300 seconds,
  // with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
  val apiKey = APIKeyParams(
      ACLs = listOf(ACL.Search),
      indices = listOf(IndexName("dev_*")),
      maxHitsPerQuery = 20,
      maxQueriesPerIPPerHour = 100,
      validity = 300
  )

  client.updateAPIKey(APIKey("YourAPIKey"), apiKey)
  ```

  ```php PHP theme={"system"}
  // Update an existing API key that is valid for 300 seconds
  $res = $client->updateApiKey('YourAPIKey', [
    'acl' => ['search']
    'validity' => 300
  ]);

  echo 'key=' . $res['key'] . "\n";

  // Update an existing index-specific API key valid for 300 seconds,
  // with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
  $res = $index->updateApiKey('YourAPIKey', [
    'acl' => ['search'],
    'validity' => 300,
    'maxQueriesPerIPPerHour' => 100,
    'maxHitsPerQuery' => 20
  ]);

  echo 'key=' . $res['key'] . "\n";
  ```

  ```python Python theme={"system"}
  # Update an existing API key that is valid for 300 seconds
  res = client.update_api_key('YourAPIKey', {
      'acl' => ['search'],    
      'validity': 300,
  })

  print('key=%s' % res['key'])

  # Update an existing index-specific API key valid for 300 seconds, with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
  res = client.update_api_key('YourAPIKey', {
      'acl' => ['search'],
      'validity': 300,
      'maxQueriesPerIPPerHour': 100,
      'maxHitsPerQuery': 20,
  })

  print('key=%s' % res['key'])
  ```

  ```ruby Ruby theme={"system"}
  # Update an existing API key that is valid for 300 seconds
  res = client.update_api_key('YourAPIKey', { 
    acl: ['search'], 
    validity: 300
  })
  puts res['key']

  # Update an existing index-specific API key:
  #  - valid for 300 seconds
  #  - rate limit of 100 calls per hour per IP
  #  - maximum of 20 hits
  #  - valid on 'your_index1' and 'your_index2'
  res = client.update_api_key('YourAPIKey', {
    acl: ['search'],
    validity: 300,
    maxQueriesPerIPPerHour: 100,
    maxHitsPerQuery: 20,
    indexes: ['your_index1', 'your_index2']
  })
  puts res['key']
  ```

  ```scala Scala theme={"system"}
  // Creates a new API key that is valid for 300 seconds
  client.execute {
    update key "YourAPIKey" `with` ApiKey(
        acl = Some(Seq(Acl.search)),
        maxHitsPerQuery = Some(0)),
        maxQueriesPerIPPerHour = Some(0),
        validity = Some(300)
    )
  }

  // Update a index-specific API key valid for 300 seconds,
  // with a rate limit of 100 calls per hour per IP and a

  val apiKey = ApiKey(
    acl = Some(Seq(Acl.search)),
    maxHitsPerQuery = Some(100)),
    maxQueriesPerIPPerHour = Some(100),
    validity = Some(300)
  )

  client.execute {
    update key "YourAPIKey" `with` apiKey from "YourIndex"
  }
  ```

  ```swift Swift theme={"system"}
  // Update an existing index-specific API key valid for 300 seconds,
  // with a rate limit of 100 calls per hour per IP and a maximum of 20 hits

  let parameters = APIKeyParameters(ACLs: [.search])
    .set(\.indices, to: ["dev_*"])
    .set(\.maxHitsPerQuery, to: 20)
    .set(\.maxQueriesPerIPPerHour, to: 100)
    .set(\.validity, to: 300)

  client.updateAPIKey("YourAPIKey", with: parameters) { result in
    if case .success(let response) = result {
    }
  }
  ```
</CodeGroup>

## Parameters

<ParamField body="apiKey" type="string" required>
  API Key to update
</ParamField>

<ParamField body="acl" type="string[]">
  Set of permissions associated with the key.

  The possible access controls are:

  * **Search** (`search`): allowed to perform search operations.
  * **Browse Index** (`browse`): allowed to retrieve all index data with the `browse` endpoint.
  * **Add records** (`addObject`): allowed to add or update records in the index.
  * **Delete records** (`deleteObject`): allowed to delete an existing record.
  * **List indices** (`listIndexes`): allowed to get a list of all existing indices.
  * **Delete index** (`deleteIndex`): allowed to delete an index.
  * **Get index settings** (`settings`): allowed to read all index settings.
  * **Set index settings** (`editSettings`): allowed to update all index settings.
  * **Use analytics API** (`analytics`): allowed to retrieve data with the Analytics API.
  * **Use personalization API** (`recommendation`): allowed to interact with the Personalization API.
  * **Use usage API** (`usage`): allowed to retrieve data with the Usage API.
  * **Access logs** (`logs`): allowed to query the logs.
  * **Get unretrievable attributes** (`seeUnretrievableAttributes`): allowed to retrieve [`unretrievableAttributes`](/doc/api-reference/api-parameters/unretrievableAttributes) for all operations that return records.
</ParamField>

<ParamField body="description" type="string">
  Specify a description to describe where the key is used.
</ParamField>

<ParamField body="indexes" type="string[]">
  Specify the list of targeted indices.
  You can target all indices starting with a prefix or ending with a suffix using the `*` character.
  For example, `dev_*` matches all indices starting with `dev_`
  and `*_dev` matches all indices ending with `_dev`.
</ParamField>

<ParamField body="maxHitsPerQuery" type="integer" default={0}>
  Specify the maximum number of hits this API key can retrieve in one call.
  This parameter can be used to protect you from attempts at retrieving your
  entire index contents by massively querying the index.

  **This must be a positive integer.**
</ParamField>

<ParamField body="maxQueriesPerIPPerHour" type="integer" default={0}>
  Specify the maximum number of API calls allowed from an IP address per hour.
  Each time an API call is performed with this key, a check is performed.
  If the IP at the source of the call did more than this number of calls in the last hour, a 429 code is returned.

  **This must be a positive integer.**

  This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index.
</ParamField>

<ParamField body="queryParameters" type="object">
  Specify the list of query parameters.
  You can force the query parameters for a query using the url string format.
  Example: "typoTolerance=strict\&ignorePlurals=false"
</ParamField>

<ParamField body="referers" type="string[]">
  Specify the list of referers.
  You can target all referers starting with a prefix, ending with a suffix using the `*` character.
  For example, `https://algolia.com/*` matches all referers starting with
  `https://algolia.com/` and `*.algolia.com` matches all referers ending with `.algolia.com`.
  To allow the domain `algolia.com`, use `*algolia.com/*`.
</ParamField>

<ParamField body="validity" type="integer">
  A Unix timestamp used to define the expiration date of the API key.

  **This must be a positive integer.**
</ParamField>

## Response

<ResponseField name="key" type="string">
  The updated key.
</ResponseField>

<ResponseField name="updatedAt" type="string">
  The date at which the key was updated.
</ResponseField>

### Response as JSON

This section shows the JSON response returned by the API.
Each API client wraps this response in language-specific objects, so the structure may vary.
To view the response, use the `getLogs` method.
Don't rely on the order of properties—JSON objects don't preserve key order.

```jsonc JSON icon=braces theme={"system"}
{
  "key": "1eb37de6308abdccf9b760ddacb418b4",
  "updatedAt": "2017-12-16T22:21:31.871Z"
}
```
