# API keys

Create and manage SWQoS API keys and separate credentials for the Management API

Source: https://zerocopy.sh/docs/api-keys

ZeroCopy uses separate credentials for SWQoS submission and account management.
[Shredstream receivers](/docs/shredstream/receivers) do not use API keys.

| Credential | Use | Where to create it |
| --- | --- | --- |
| SWQoS API key | Submit transactions and bundles, and query the send service | Your team's **API keys** page |
| Management key | Manage keys, read usage and manage partner domains through `/api/v1` | Your team's **API keys** page |

Keep both credentials in server code. An SWQoS API key cannot authenticate Management API
requests.

## SWQoS API keys [#swqos-keys]

Create a team in the [console](https://console.zerocopy.sh), then choose **Create API key**.
Team admins and developers can create keys. Save the secret when it appears; it is shown
only once. By default, secrets are 32 characters: `zc_live_` followed by 24 securely
generated random ASCII letters or digits. White label partners can request a
[custom prefix for customer keys](/docs/account/white-label#customer-key-prefixes);
your team's own sending keys keep the default format.

Teams start with [10 sending-key slots](/docs/swqos/limits#keys). Paused keys count toward the
limit; expired, revoked and [white-label customer keys](/docs/account/white-label#customer-keys)
do not. To increase the limit, choose **Request more slots** on **API keys**. Enter the
desired total, not the number of additional slots. The request stays on the page until reviewed.
To rotate a key, create a replacement, update your application, then revoke the old key.

### HTTP [#http]

Send the key in the `x-api-key` header. This keeps it out of request URLs.
The [authentication reference](/docs/reference/json-rpc#authentication) covers compatibility
forms and their precedence.

Set `SWQOS_API_KEY` to your key. Rust and Go use the
[example project](/docs/reference/json-rpc#example-project); TypeScript uses `fetch`.

```rust title="src/bin/api_key_header.rs" tab="Rust" tab-group="language"
use serde_json::{Value, json};
use swqos_examples::swqos::{Result, required};

#[tokio::main]
async fn main() -> Result<()> {
    let response = reqwest::Client::new()
        .post("https://sol.zerocopy.sh")
        .header("x-api-key", required("SWQOS_API_KEY")?)
        .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": "getTipAccounts" }))
        .send()
        .await?;
    let status = response.status();
    let body = response.text().await?;
    let reply: Value = serde_json::from_str(&body)
        .map_err(|error| format!("HTTP {status}: {error}; body: {body}"))?;
    if !status.is_success() || reply.get("error").is_some_and(|error| !error.is_null()) {
        return Err(format!("HTTP {status}: {reply}").into());
    }
    println!("{}", serde_json::to_string_pretty(&reply)?);
    Ok(())
}
```

```go title="api-key-header/main.go" tab="Go" tab-group="language"
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strings"

	swqos "swqos-examples"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	apiKey, err := swqos.Required("SWQOS_API_KEY")
	if err != nil {
		return err
	}
	request, err := http.NewRequest(http.MethodPost, "https://sol.zerocopy.sh",
		strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"getTipAccounts"}`))
	if err != nil {
		return err
	}
	request.Header.Set("x-api-key", apiKey)
	request.Header.Set("Content-Type", "application/json")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	var reply map[string]any
	if err := json.NewDecoder(response.Body).Decode(&reply); err != nil {
		return fmt.Errorf("HTTP %d: %w", response.StatusCode, err)
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 || reply["error"] != nil {
		return fmt.Errorf("HTTP %d: %v", response.StatusCode, reply)
	}
	output, err := json.MarshalIndent(reply, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println(string(output))
	return nil
}
```

```ts title="api-key-header.ts" tab="TypeScript" tab-group="language"
const apiKey = process.env.SWQOS_API_KEY
if (!apiKey) throw new Error('set SWQOS_API_KEY')

const response = await fetch('https://sol.zerocopy.sh', {
  method: 'POST',
  headers: { 'x-api-key': apiKey, 'content-type': 'application/json' },
  body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getTipAccounts' }),
})
const body = await response.text()
let reply: { error?: unknown }
try {
  reply = JSON.parse(body)
} catch {
  throw new Error(`HTTP ${response.status}: invalid JSON; body: ${body}`)
}
if (!response.ok || reply.error != null) {
  throw new Error(`HTTP ${response.status}: ${JSON.stringify(reply)}`)
}
console.log(JSON.stringify(reply, null, 2))

export {}
```

```sh title="HTTP key header" tab="cURL" tab-group="language"
curl --fail-with-body -sS 'https://sol.zerocopy.sh' \
  -H "x-api-key: $SWQOS_API_KEY" \
  -H 'content-type: application/json' \
  --data '{"jsonrpc":"2.0","id":1,"method":"getTipAccounts"}'
```

All HTTP routes need a key except `GET /health`. Use HTTPS. Hosted endpoints do not
provide CORS headers. See the [HTTP route reference](/docs/reference/http).

### QUIC [#quic]

Put the key in the client certificate's first common name (`CN`). A self-signed
certificate works. Follow the [QUIC connection setup](/docs/reference/quic#connect) for
ALPN and server certificate verification.

### Local agent [#agent]

The [agent](/docs/swqos/agent/install-and-run) uses the key in its licensed executable.
Local HTTP and QUIC accept any key or none, and IPC carries none. A request header
cannot switch the agent to another key. Restrict access to these listeners.
Existing agent builds require a `zc_live_` license key. White label customer keys with
custom prefixes are for hosted endpoints, not these builds.

### Declared tips and refusals [#refusals]

Using a key does not enable declared tips. Ask for
[declared tip access and payment](/docs/account/billing#declared-tips) through [Requests in the console](https://console.zerocopy.sh) first.

A missing, unknown or revoked key returns
[`unauthorized`](/docs/reference/errors#unauthorized). Support can pause a key; it returns
[`key_paused`](/docs/reference/errors#key_paused) until resumed. An overdue declared tip payment returns
[`payment_required`](/docs/reference/errors#payment_required) on submissions; queries remain
available. Resolve payment through your agreed billing setup or
ask for help on [Discord](https://discord.gg/zerocopy).

## Management keys [#management-keys]

Create a management key on your team's **API keys** page. Only team admins can create
or revoke these keys. Creation requires recent identity verification. Save the secret
when it appears. Management key secrets start with `zc_mgmt_`.

Choose a lifetime of 30, 90 or 365 days and the [scopes](/docs/reference/management-api#scopes)
the integration needs. You can restrict the key to IPv4 or IPv6 addresses and ranges.
A team can have up to 25 live management keys.

Management keys belong to the team and keep working when their creator leaves or
changes role. To change a key's scopes or restrictions, create a replacement, update
the integration, then revoke the old key. Revocation, expiry and team closure stop
management authentication.

Send the key as `Authorization: Bearer YOUR_MANAGEMENT_KEY` to the console's origin.
Use the [Management API guide](/docs/account/management-api) for examples and idempotent
requests, and the [reference](/docs/reference/management-api) for endpoints and response fields.
