> 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.

# Create an API key

POST https://api-gateway.merge.dev/v1/keys
Content-Type: application/json

Mint a new API key, optionally scoped to a project, capped with `limit` and `limit_reset`, or restricted with `allowed_models`. The raw key is returned once, in the `key` field.

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

## Authentication

- `Authorization` header (bearer token, required) — A management key (prefixed `mgmt_`), created on the dashboard's **API keys** page under **Management keys**. Distinct from a regular gateway API key, and never used to call models.

## Request

### Body (application/json)

This endpoint expects a CreateKeyRequest.

- `name` (string, optional, nullable) — A name for the key, for example `customer-acme` or `alice@acme.com`. Shown in the dashboard and usage views.
- `limit` (double, optional, nullable) — Optional spend cap in USD over the reset window.
- `limit_reset` (enum, optional) — Window the spend cap resets on; defaults to monthly.
  - Allowed values: `daily`, `weekly`, `monthly`
- `project_id` (string, optional, nullable) — Project to scope the key to; a key's project can't be changed after creation.
- `allowed_models` (list of string, optional, nullable) — Canonical `provider/model` IDs this key may call, where a trailing `*` matches by prefix; omit or send null for no restriction, and an empty list blocks every model.

## Response

### 201

The created key, including the raw secret.

- `hash` (string, required) — Stable identifier for the key. A one-way hash, not the secret, so it is safe to store and log. Use it in get, update, and delete calls.
- `label` (string, required) — Display label (the key's public prefix, e.g. `mg_8Kx2pQ`). Not the secret.
- `disabled` (boolean, required) — Whether the key is disabled. A disabled key cannot call the gateway but is not deleted.
- `usage` (double, required) — Spend in USD in the current reset window.
- `key` (string, required) — The raw API key (prefixed `mg_`). Shown exactly once, at creation. Store it now; it cannot be retrieved later.
- `name` (string, optional, nullable) — User-set name for the key.
- `limit` (double, optional, nullable) — Spend cap in USD over the reset window. Null means no cap.
- `limit_reset` (enum, optional) — Window the spend cap resets on. Resets at midnight UTC.
  - Allowed values: `daily`, `weekly`, `monthly`
- `limit_remaining` (double, optional, nullable) — Remaining spend in USD before the cap. Null when no limit is set.
- `created_at` (datetime, optional, nullable) — When the key was created.
- `project_id` (string, optional, nullable) — Project the key is scoped to, or null for an organization-wide key.
- `allowed_models` (list of string, optional, nullable) — Models the key may call; null means unrestricted and an empty list blocks every model.
- `routing_policy_id` (string, optional, nullable) — Routing policy bound to the key, if any.

## Errors

### 400 Bad Request Error

Invalid request, for example an unsupported `limit_reset`, an inactive project, or an `allowed_models` entry that can never match.

- `detail` (string, optional) — Human-readable error message.

### 401 Unauthorized Error

Missing or invalid management key.

- `detail` (string, optional) — Human-readable error message.

### 403 Forbidden Error

The management key lacks the `manage_keys` scope, or the organization has no payment method on file (`payment_method_required`).

- `detail` (string, optional) — Human-readable error message.

### 404 Not Found Error

`project_id` doesn't match a project in this organization.

- `detail` (string, optional) — Human-readable error message.

## Examples

**Request**

```json
{
  "name": "customer-acme",
  "limit": 50,
  "limit_reset": "monthly",
  "allowed_models": [
    "anthropic/claude-sonnet-4-6",
    "openai/*"
  ]
}
```

**Response**

```json
{
  "hash": "a1b2c3d4e5f6",
  "label": "mg_8Kx2pQ",
  "disabled": false,
  "usage": 12.4,
  "key": "mg_8Kx2pQrShT1uVwXyZ...",
  "name": "customer-acme",
  "limit": 50,
  "limit_reset": "monthly",
  "limit_remaining": 37.6,
  "created_at": "2026-06-02T17:04:00Z",
  "project_id": null,
  "allowed_models": [
    "anthropic/claude-sonnet-4-6",
    "openai/*"
  ],
  "routing_policy_id": null
}
```

**SDK Code**

```python keys_create_example
import requests

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

payload = {
    "name": "customer-acme",
    "limit": 50,
    "limit_reset": "monthly",
    "allowed_models": ["anthropic/claude-sonnet-4-6", "openai/*"]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript keys_create_example
const url = 'https://api-gateway.merge.dev/v1/keys';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"name":"customer-acme","limit":50,"limit_reset":"monthly","allowed_models":["anthropic/claude-sonnet-4-6","openai/*"]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go keys_create_example
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

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

	payload := strings.NewReader("{\n  \"name\": \"customer-acme\",\n  \"limit\": 50,\n  \"limit_reset\": \"monthly\",\n  \"allowed_models\": [\n    \"anthropic/claude-sonnet-4-6\",\n    \"openai/*\"\n  ]\n}")

	req, _ := http.NewRequest("POST", 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 keys_create_example
require 'uri'
require 'net/http'

url = URI("https://api-gateway.merge.dev/v1/keys")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"name\": \"customer-acme\",\n  \"limit\": 50,\n  \"limit_reset\": \"monthly\",\n  \"allowed_models\": [\n    \"anthropic/claude-sonnet-4-6\",\n    \"openai/*\"\n  ]\n}"

response = http.request(request)
puts response.read_body
```

```java keys_create_example
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api-gateway.merge.dev/v1/keys")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"customer-acme\",\n  \"limit\": 50,\n  \"limit_reset\": \"monthly\",\n  \"allowed_models\": [\n    \"anthropic/claude-sonnet-4-6\",\n    \"openai/*\"\n  ]\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api-gateway.merge.dev/v1/keys', [
  'body' => '{
  "name": "customer-acme",
  "limit": 50,
  "limit_reset": "monthly",
  "allowed_models": [
    "anthropic/claude-sonnet-4-6",
    "openai/*"
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp keys_create_example
using RestSharp;

var client = new RestClient("https://api-gateway.merge.dev/v1/keys");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"customer-acme\",\n  \"limit\": 50,\n  \"limit_reset\": \"monthly\",\n  \"allowed_models\": [\n    \"anthropic/claude-sonnet-4-6\",\n    \"openai/*\"\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift keys_create_example
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "customer-acme",
  "limit": 50,
  "limit_reset": "monthly",
  "allowed_models": ["anthropic/claude-sonnet-4-6", "openai/*"]
] as [String : Any]

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

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