> This page is for Gateway.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.merge.dev/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.merge.dev/_mcp/server.

# Update Key

PATCH https://api-gateway.merge.dev/v1/keys/{key_hash}
Content-Type: application/json

Update a key's name, disabled state, spend limit, model allowlist,
routing policy binding or expiry. Only the fields you send change; send
null to remove a limit, allowlist, binding or expiry. A key's project
can't be changed.

Reference: https://docs.merge.dev/merge-gateway/management-api/api-keys/update-key

## Authentication

- `Authorization` header (bearer token, required) — A management key (`mgmt_...`), sent as `Authorization: Bearer <key>`. Reading /v1/routing-policies also accepts the organization's gateway API keys; writing there needs a management key.

## Request

### Path parameters

- `key_hash` (string, required) — The key's `hash` from a create or list response.

### Body (application/json)

This endpoint expects a KeyUpdateRequest.

- `allowed_models` (list of string, optional, nullable) — Replaces the model allowlist. Send null to remove the restriction, or an empty list to block every model.
- `budget_group_id` (string, optional, nullable) — Managed by Merge for Workforce; sending this field is a 400.
- `disabled` (boolean, optional, nullable) — Send true to disable the key, false to enable it again.
- `expires_at` (datetime, optional, nullable) — When the key stops working. Null means it never expires. Must be in the future; a value without an offset is UTC. Send null to remove the expiry; omit it to leave the expiry unchanged.
- `limit` (double, optional, nullable) — New spend cap in USD. Omit to keep the current cap; send null to remove it.
- `limit_reset` (enum, optional, nullable) — New window for the spend cap: `daily`, `weekly` or `monthly`, reset at midnight UTC.
  - Allowed values: `daily`, `weekly`, `monthly`
- `name` (string, optional, nullable) — New name for the key.
- `project_id` (string, optional, nullable) — Can't be changed after creation; sending a value is a 400.
- `routing_policy_id` (string, optional, nullable) — Routing policy to bind the key to. Send null to unbind it, so the key falls back to its project's or the organization's default.

## Response

### 200

The updated API key

- `byok_usage` (double, required) — The part of usage from requests that ran on the organization's own provider credentials (BYOK).
- `byok_usage_daily` (double, required) — The BYOK part of usage_daily.
- `byok_usage_monthly` (double, required) — The BYOK part of usage_monthly.
- `byok_usage_weekly` (double, required) — The BYOK part of usage_weekly.
- `creator_user_id` (string, required, nullable) — The dashboard user who created the key. Null for keys created with a management key.
- `disabled` (boolean, required) — Whether the key is disabled. A disabled key can't call the gateway but isn't deleted.
- `hash` (string, required) — Stable identifier for the key: the SHA-256 hash of the raw key, as 64 hex characters. Not the secret, so it's safe to store and log. Use it in get, update and delete calls.
- `label` (string, required) — Display label: the key's first characters, like `mg_8Kx2pQr`. Not the secret.
- `usage` (double, required) — Spend in USD in the current `limit_reset` window.
- `usage_daily` (double, required) — USD spend today.
- `usage_monthly` (double, required) — USD spend since the 1st of the month.
- `usage_weekly` (double, required) — USD spend since Monday.
- `allowed_models` (list of string, optional, nullable) — Models the key may call. Null means unrestricted; an empty list blocks every model.
- `budget_group_id` (string, optional, nullable) — The Merge for Workforce budget group the key draws down.
- `created_at` (datetime, optional, nullable) — When the key was created.
- `expires_at` (datetime, optional, nullable) — When the key stops working. Null means it never expires.
- `limit` (double, optional, nullable) — Spend cap in USD over the `limit_reset` window. Null means no cap.
- `limit_remaining` (double, optional, nullable) — Spend left in USD before the cap: `limit` minus `usage`, never below 0. Null when there's no limit.
- `limit_reset` (enum, optional, nullable) — The window the spend cap applies to, reset at midnight UTC: `daily`, `weekly` (from Monday) or `monthly` (from the 1st). Monthly when unset.
  - Allowed values: `daily`, `weekly`, `monthly`
- `name` (string, optional, nullable) — The key's name.
- `project_id` (string, optional, nullable) — Project the key is scoped to, or null for an organization-wide key. Can't be changed after creation.
- `routing_policy_id` (string, optional, nullable) — Routing policy bound to the key, if any.
- `updated_at` (datetime, optional, nullable) — When the key last changed.

## Errors

### 400 Bad Request Error

The request breaks a rule: an unknown limit_reset, a limit that isn't positive, a model the key can't be limited to, an inactive project or routing policy, or a field that can't be changed.

- `detail` (ErrorResponseDetail, required) — A message, or an object with a `code` to branch on and a `message`.

### 401 Unauthorized Error

The key is missing or invalid.

- `detail` (ErrorResponseDetail, required) — A message, or an object with a `code` to branch on and a `message`.

### 403 Forbidden Error

The key lacks the scope this route needs, or the change is not allowed.

- `detail` (ErrorResponseDetail, required) — A message, or an object with a `code` to branch on and a `message`.

### 404 Not Found Error

The resource does not exist in the key's organization.

- `detail` (ErrorResponseDetail, required) — A message, or an object with a `code` to branch on and a `message`.

### 422 Unprocessable Entity Error

Validation Error

- `detail` (list of ValidationError, optional)

### 502 Bad Gateway Error

The gateway could not be updated. Retrying the same request is safe.

- `detail` (ErrorResponseDetail, required) — A message, or an object with a `code` to branch on and a `message`.

## Types

### ErrorResponseDetail

A message, or an object with a `code` to branch on and a `message`.

### ValidationError

- `loc` (list of ValidationErrorLocItems, required)
- `msg` (string, required)
- `type` (string, required)
- `ctx` (ValidationErrorCtx, optional)
- `input` (any, optional)

### ErrorDetail

A structured error. Some carry extra fields, like `count`.

- `code` (string, required) — A stable code to branch on, like `payment_method_required`.
- `message` (string, required) — A human-readable explanation.

### ValidationErrorLocItems

### ValidationErrorCtx

## Examples

**Request**

```json
{
  "disabled": true,
  "limit": 100
}
```

**Response**

```json
{
  "byok_usage": 4.1,
  "byok_usage_daily": 0.3,
  "byok_usage_monthly": 4.1,
  "byok_usage_weekly": 1.05,
  "creator_user_id": null,
  "disabled": false,
  "hash": "5f3c8a1e9b2d4f6a7c0e1b3d5f7a9c2e4b6d8f0a1c3e5b7d9f2a4c6e8b0d1f3a",
  "label": "mg_8Kx2pQr",
  "usage": 12.4,
  "usage_daily": 0.82,
  "usage_monthly": 12.4,
  "usage_weekly": 3.15,
  "allowed_models": [
    "anthropic/claude-sonnet-4-6",
    "openai/*"
  ],
  "budget_group_id": null,
  "created_at": "2026-06-02T17:04:00Z",
  "expires_at": null,
  "limit": 50,
  "limit_remaining": 37.6,
  "limit_reset": "monthly",
  "name": "customer-acme",
  "project_id": "8b6f2d4a-1c3e-4b5a-9f7d-2e0c6a8b4d91",
  "routing_policy_id": null,
  "updated_at": "2026-09-14T09:30:00Z"
}
```

**SDK Code**

```python
import requests

url = "https://api-gateway.merge.dev/v1/keys/key_hash"

payload = {
    "disabled": True,
    "limit": 100
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://api-gateway.merge.dev/v1/keys/key_hash';
const options = {
  method: 'PATCH',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"disabled":true,"limit":100}'
};

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://api-gateway.merge.dev/v1/keys/key_hash"

	payload := strings.NewReader("{\n  \"disabled\": true,\n  \"limit\": 100\n}")

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

	req.Header.Add("Authorization", "Bearer <token>")
	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://api-gateway.merge.dev/v1/keys/key_hash")

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

request = Net::HTTP::Patch.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"disabled\": true,\n  \"limit\": 100\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.patch("https://api-gateway.merge.dev/v1/keys/key_hash")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"disabled\": true,\n  \"limit\": 100\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('PATCH', 'https://api-gateway.merge.dev/v1/keys/key_hash', [
  'body' => '{
  "disabled": true,
  "limit": 100
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api-gateway.merge.dev/v1/keys/key_hash");
var request = new RestRequest(Method.PATCH);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"disabled\": true,\n  \"limit\": 100\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "disabled": true,
  "limit": 100
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api-gateway.merge.dev/v1/keys/key_hash")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "PATCH"
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()
```