# Create an API key

Creates an own API key and returns its secret once. Use Create a customer key for customer keys.

Source: https://zerocopy.sh/docs/reference/management-api/create-an-api-key

`POST https://console.zerocopy.sh/api/v1/keys`

Authentication: API key, one of: `Authorization: Bearer` header.

## Parameters

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `Idempotency-Key` | header | string | no | Makes a retry return the first response instead of creating another key |

## Request body (`application/json`)

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | yes | minLength: `1`. maxLength: `64`. |
| `products` | array of `"send"` or `"jsonrpc"` or `"ws"` or `"grpc"` or `"deshred"` or `"das"` or `"history"` | no | Default `["send"]`. minItems: `1`. maxItems: `7`. |
| `expires_in_days` | `0` or `7` or `30` or `90` or `365` | no | Days from now until the key stops working; 0 never Default `0`. |
| `rules` | object | no | Rules for a key's read products; a request must also pass the endpoint's own |
| `rules.endpoints` | object or object | no | Endpoints the key reads through: every one, or only those listed Default `{"mode":"all"}`. |
| `rules.endpoints.mode` | `"all"` | yes |  |
| `rules.endpoints.mode` | `"only"` | yes |  |
| `rules.endpoints.ids` | array of string | yes | maxItems: `256`. |
| `rules.ips` | array of string | no | IPv4 addresses or CIDR ranges requests may come from; empty allows any Default `[]`. maxItems: `256`. |
| `rules.origins` | array of string | no | Web origins requests may carry; empty allows any Default `[]`. maxItems: `256`. |
| `rules.methods` | object | no | JSON-RPC methods allowed or refused Default `{"mode":"all","list":[]}`. |
| `rules.methods.mode` | `"all"` or `"allow"` or `"deny"` | yes |  |
| `rules.methods.list` | array of string | no | Default `[]`. maxItems: `256`. |

```json
{
  "name": "production",
  "products": [
    "send"
  ],
  "expires_in_days": 30
}
```

## Responses

### 201

The key and its secret, shown once

| Header | Type | Description |
| --- | --- | --- |
| `ETag` | string | Strong validator of the returned key state |

Content type: `application/json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `key` | object | yes |  |
| `key.id` | string | yes |  |
| `key.name` | string or null | yes |  |
| `key.products` | array of `"send"` or `"jsonrpc"` or `"ws"` or `"grpc"` or `"deshred"` or `"das"` or `"history"` | yes |  |
| `key.created_at` | string (date-time) or null | yes |  |
| `key.expires_at` | string (date-time) or null | yes |  |
| `key.paused_at` | string (date-time) or null | yes | When the key was paused, or null if it is not paused |
| `key.revoked` | boolean | yes |  |
| `key.revoked_at` | string (date-time) or null | yes |  |
| `key.rules` | object | yes | Rules for a key's read products; a request must also pass the endpoint's own |
| `key.rules.endpoints` | object or object | yes | Endpoints the key reads through: every one, or only those listed Default `{"mode":"all"}`. |
| `key.rules.endpoints.mode` | `"all"` | yes |  |
| `key.rules.endpoints.mode` | `"only"` | yes |  |
| `key.rules.endpoints.ids` | array of string | yes | maxItems: `256`. |
| `key.rules.ips` | array of string | yes | IPv4 addresses or CIDR ranges requests may come from; empty allows any Default `[]`. maxItems: `256`. |
| `key.rules.origins` | array of string | yes | Web origins requests may carry; empty allows any Default `[]`. maxItems: `256`. |
| `key.rules.methods` | object | yes | JSON-RPC methods allowed or refused Default `{"mode":"all","list":[]}`. |
| `key.rules.methods.mode` | `"all"` or `"allow"` or `"deny"` | yes |  |
| `key.rules.methods.list` | array of string | yes | Default `[]`. maxItems: `256`. |
| `key.send` | object or null | yes | The key's sending settings; null without the `send` product |
| `key.send.rate_per_second` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `key.send.min_tip_lamports` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `secret` | string | yes | The key's secret, returned once and never again |

```json title="Created key and its one-time secret"
{
  "key": {
    "id": "key_012345abcdef",
    "name": "production",
    "products": [
      "send"
    ],
    "created_at": "2026-11-12T09:00:00Z",
    "expires_at": "2026-12-12T09:00:00Z",
    "paused_at": null,
    "revoked": false,
    "revoked_at": null,
    "rules": {
      "endpoints": {
        "mode": "all"
      },
      "ips": [
        "203.0.113.10/32"
      ],
      "origins": [
        "https://dashboard.example"
      ],
      "methods": {
        "mode": "allow",
        "list": [
          "getBalance"
        ]
      }
    },
    "send": {
      "rate_per_second": 50,
      "min_tip_lamports": 1000000
    }
  },
  "secret": "zc_live_ExampleOnly0123456789abc"
}
```

### 400

A refusal; `code` is stable

Content type: `application/problem+json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | yes |  |
| `status` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `code` | string | yes | Stable, for programs to branch on |
| `detail` | string | yes |  |
| `request_id` | string | yes |  |
| `errors` | array of object | no |  |
| `errors[].path` | string | yes |  |
| `errors[].message` | string | yes |  |

```json title="Invalid request"
{
  "title": "Bad request",
  "status": 400,
  "code": "invalid_request",
  "detail": "The request does not match the schema.",
  "request_id": "8d4ac3b9-e451-4ca4-9a7f-b3928f0b1672"
}
```

### 401

A refusal; `code` is stable

Content type: `application/problem+json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | yes |  |
| `status` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `code` | string | yes | Stable, for programs to branch on |
| `detail` | string | yes |  |
| `request_id` | string | yes |  |
| `errors` | array of object | no |  |
| `errors[].path` | string | yes |  |
| `errors[].message` | string | yes |  |

```json title="Unknown, revoked or expired management key"
{
  "title": "Unauthorized",
  "status": 401,
  "code": "unauthorized",
  "detail": "The management key is unknown, revoked or expired.",
  "request_id": "8d4ac3b9-e451-4ca4-9a7f-b3928f0b1672"
}
```

### 403

A refusal; `code` is stable

Content type: `application/problem+json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | yes |  |
| `status` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `code` | string | yes | Stable, for programs to branch on |
| `detail` | string | yes |  |
| `request_id` | string | yes |  |
| `errors` | array of object | no |  |
| `errors[].path` | string | yes |  |
| `errors[].message` | string | yes |  |

```json title="IP restriction"
{
  "title": "Forbidden",
  "status": 403,
  "code": "forbidden_ip",
  "detail": "This key does not allow requests from this address.",
  "request_id": "8d4ac3b9-e451-4ca4-9a7f-b3928f0b1672"
}
```

### 404

A refusal; `code` is stable

Content type: `application/problem+json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | yes |  |
| `status` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `code` | string | yes | Stable, for programs to branch on |
| `detail` | string | yes |  |
| `request_id` | string | yes |  |
| `errors` | array of object | no |  |
| `errors[].path` | string | yes |  |
| `errors[].message` | string | yes |  |

```json title="Unknown route"
{
  "title": "Not found",
  "status": 404,
  "code": "not_found",
  "detail": "No such route.",
  "request_id": "8d4ac3b9-e451-4ca4-9a7f-b3928f0b1672"
}
```

### 409

A refusal; `code` is stable

Content type: `application/problem+json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | yes |  |
| `status` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `code` | string | yes | Stable, for programs to branch on |
| `detail` | string | yes |  |
| `request_id` | string | yes |  |
| `errors` | array of object | no |  |
| `errors[].path` | string | yes |  |
| `errors[].message` | string | yes |  |

```json title="Idempotency key reused for a different request"
{
  "title": "Conflict",
  "status": 409,
  "code": "idempotency_key_reused",
  "detail": "This Idempotency-Key was used for a different request.",
  "request_id": "8d4ac3b9-e451-4ca4-9a7f-b3928f0b1672"
}
```

### 413

A refusal; `code` is stable

Content type: `application/problem+json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | yes |  |
| `status` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `code` | string | yes | Stable, for programs to branch on |
| `detail` | string | yes |  |
| `request_id` | string | yes |  |
| `errors` | array of object | no |  |
| `errors[].path` | string | yes |  |
| `errors[].message` | string | yes |  |

```json title="Body exceeds the request limit"
{
  "title": "Content too large",
  "status": 413,
  "code": "body_too_large",
  "detail": "The request body exceeds 64 KiB.",
  "request_id": "8d4ac3b9-e451-4ca4-9a7f-b3928f0b1672"
}
```

### 429

A refusal; `code` is stable

Content type: `application/problem+json`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | yes |  |
| `status` | integer | yes | minimum: `-9007199254740991`. maximum: `9007199254740991`. |
| `code` | string | yes | Stable, for programs to branch on |
| `detail` | string | yes |  |
| `request_id` | string | yes |  |
| `errors` | array of object | no |  |
| `errors[].path` | string | yes |  |
| `errors[].message` | string | yes |  |

```json title="Management write limit"
{
  "title": "Too many requests",
  "status": 429,
  "code": "rate_limited",
  "detail": "This key may make 60 such requests a minute.",
  "request_id": "8d4ac3b9-e451-4ca4-9a7f-b3928f0b1672"
}
```

## Code samples

```rust title="Rust"
// src/bin/management_create_key.rs
// Builds on the example project (/reference/json-rpc#example-project).
use swqos_examples::swqos::{Result, required};

use serde::Serialize;

#[derive(Serialize)]
struct KeyCreate {
    name: String,
    products: [&'static str; 1],
    expires_in_days: u16,
}

#[tokio::main]
async fn main() -> Result<()> {
    let name = required("KEY_NAME")?.trim().to_owned();
    if !(1..=64).contains(&name.chars().count()) {
        return Err("KEY_NAME must have 1 to 64 characters after trimming".into());
    }
    let payload = KeyCreate { name, products: ["send"], expires_in_days: 30 };
    let endpoint = reqwest::Url::parse("https://console.zerocopy.sh/api/v1/keys")?;
    let request = reqwest::Client::new()
        .post(endpoint)
        .bearer_auth(required("MANAGEMENT_API_KEY")?);
    // Reuse this key and the same body when retrying this creation attempt.
    let request = request.header("Idempotency-Key", required("KEY_REQUEST_ID")?);
    let request = request.json(&payload);
    let response = request.send().await?;
    let status = response.status();
    let request_id = response.headers().get("Request-Id")
        .map(|value| value.to_str()).transpose()?.unwrap_or("<missing>").to_owned();
    if let Some(etag) = response.headers().get("ETag") {
        eprintln!("ETag: {}", etag.to_str()?);
    }
    let body = response.text().await?;
    if !status.is_success() {
        return Err(format!("HTTP {status}; Request-Id: {request_id}; {body}").into());
    }
    eprintln!("Request-Id: {request_id}");
    println!("{body}");
    Ok(())
}
```

```go title="Go"
// management_create_key/main.go
package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "bytes"
    "encoding/json"
    "strings"
    "unicode/utf8"
)

type KeyCreate struct {
    Name string `json:"name"`
    Products []string `json:"products"`
    ExpiresInDays uint16 `json:"expires_in_days"`
}

func required(name string) (string, error) {
    value := os.Getenv(name)
    if value == "" {
        return "", fmt.Errorf("set %s", name)
    }
    return value, nil
}

func run() error {
    apiKey, err := required("MANAGEMENT_API_KEY")
    if err != nil {
        return err
    }
    // Reuse this key and the same body when retrying this creation attempt.
    idempotencyKey, err := required("KEY_REQUEST_ID")
    if err != nil {
        return err
    }
    name, err := required("KEY_NAME")
    if err != nil {
        return err
    }
    name = strings.TrimSpace(name)
    if length := utf8.RuneCountInString(name); length < 1 || length > 64 {
        return fmt.Errorf("KEY_NAME must have 1 to 64 characters after trimming")
    }
    payload := KeyCreate{Name: name, Products: []string{"send"}, ExpiresInDays: 30}
    endpoint, err := url.Parse("https://console.zerocopy.sh/api/v1/keys")
    if err != nil {
        return err
    }
    encoded, err := json.Marshal(payload)
    if err != nil {
        return err
    }
    request, err := http.NewRequest(http.MethodPost, endpoint.String(), bytes.NewReader(encoded))
    if err != nil {
        return err
    }
    request.Header.Set("Authorization", "Bearer "+apiKey)
    request.Header.Set("Idempotency-Key", idempotencyKey)
    request.Header.Set("Content-Type", "application/json")
    response, err := http.DefaultClient.Do(request)
    if err != nil {
        return err
    }
    defer response.Body.Close()
    requestID := response.Header.Get("Request-Id")
    body, err := io.ReadAll(response.Body)
    if err != nil {
        return fmt.Errorf("Request-Id: %s: %w", requestID, err)
    }
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        return fmt.Errorf("HTTP %d; Request-Id: %s; %s", response.StatusCode, requestID, body)
    }
    fmt.Fprintln(os.Stderr, "Request-Id:", requestID)
    if etag := response.Header.Get("ETag"); etag != "" {
        fmt.Fprintln(os.Stderr, "ETag:", etag)
    }
    fmt.Println(string(body))
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
```

```ts title="TypeScript"
// management-create-key.ts
export {}

type KeyCreate = { name: string; products: ['send']; expires_in_days: 30 }

function required(name: string): string {
  const value = process.env[name]
  if (!value) throw new Error(`set ${name}`)
  return value
}

const name: string = required('KEY_NAME').trim()
if (Array.from(name).length < 1 || Array.from(name).length > 64) {
  throw new Error('KEY_NAME must have 1 to 64 characters after trimming')
}
const payload: KeyCreate = { name, products: ['send'], expires_in_days: 30 }
const endpoint = new URL('https://console.zerocopy.sh/api/v1/keys')
const headers: Record<string, string> = {
  Authorization: `Bearer ${required('MANAGEMENT_API_KEY')}`,
}
// Reuse this key and the same body when retrying this creation attempt.
headers['Idempotency-Key'] = required('KEY_REQUEST_ID')
headers['Content-Type'] = 'application/json'
const response = await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify(payload) })
const requestId = response.headers.get('Request-Id')
const body = await response.text()
if (!response.ok) {
  throw new Error(`HTTP ${response.status}; Request-Id: ${requestId}; ${body}`)
}
console.error('Request-Id:', requestId)
const etag = response.headers.get('ETag')
if (etag) console.error('ETag:', etag)
console.log(body)
```
