# Authentication

> Send your API key with every request.

Source: https://docs.peak.fo/docs/authentication

Every request needs your API key. Create one in [Dashboard → API keys](https://peak.fo/dashboard/keys). Keys start with `pk_`.

## Send the key [#send-the-key]

Put the key in the `X-API-Key` header. If your HTTP client prefers it, an `Authorization` header with a Bearer token works too.

```http tab="X-API-Key"
X-API-Key: pk_your_api_key
```

```http tab="Authorization"
Authorization: Bearer pk_your_api_key
```

If you send both, `X-API-Key` is used.

## Check your key [#check-your-key]

`GET /balance` is the simplest authenticated call. It costs nothing and tells you what the key can spend. Replace `pk_your_api_key` with your key.

The Python examples use [requests](https://requests.readthedocs.io) (`pip install requests`). The Go examples use [tls-client](https://github.com/bogdanfinn/tls-client) (`go get github.com/bogdanfinn/tls-client`, Go 1.27+).

```bash tab="cURL" tab-group="language"
curl https://api.peak.fo/balance \
  -H "X-API-Key: pk_your_api_key"
```

```python tab="Python" tab-group="language"
import requests

API_KEY = "pk_your_api_key"


def get_balance() -> dict:
    """Returns your balance, or the error if the key doesn't work."""
    resp = requests.get(
        "https://api.peak.fo/balance",
        headers={"X-API-Key": API_KEY},
        timeout=30,
    )
    return resp.json()


if __name__ == "__main__":
    print(get_balance())
```

```js tab="JavaScript" tab-group="language"
const API_KEY = "pk_your_api_key";

// Returns your balance, or the error if the key doesn't work.
async function getBalance() {
  const resp = await fetch("https://api.peak.fo/balance", {
    headers: { "X-API-Key": API_KEY },
  });
  return resp.json();
}

console.log(await getBalance());
```

```go tab="Go" tab-group="language"
package main

import (
	"encoding/json"
	"fmt"
	"log"

	http "github.com/bogdanfinn/fhttp"
	tls_client "github.com/bogdanfinn/tls-client"
	"github.com/bogdanfinn/tls-client/profiles"
)

const apiKey = "pk_your_api_key"

// Response is the body of every Peak Solutions response.
type Response struct {
	Success   bool            `json:"success"`
	Data      json.RawMessage `json:"data,omitempty"`
	Error     string          `json:"error,omitempty"`
	ErrorCode string          `json:"error_code,omitempty"`
}

// getBalance returns your balance, or the error if the key doesn't work.
func getBalance(client tls_client.HttpClient) (*Response, error) {
	req, err := http.NewRequest(http.MethodGet, "https://api.peak.fo/balance", nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-API-Key", apiKey)

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var out Response
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return nil, fmt.Errorf("HTTP %d: %w", resp.StatusCode, err)
	}
	return &out, nil
}

func main() {
	client, err := tls_client.NewHttpClient(tls_client.NewNoopLogger(),
		tls_client.WithTimeoutSeconds(30),
		tls_client.WithClientProfile(profiles.Chrome_152),
	)
	if err != nil {
		log.Fatal(err)
	}

	balance, err := getBalance(client)
	if err != nil {
		log.Fatal(err)
	}

	out, _ := json.MarshalIndent(balance, "", "  ")
	fmt.Println(string(out))
}
```

If the key works, you get `"success": true` and your balance. [Balance](/docs/api/balance) lists every field.

## Errors [#errors]

A key that can't be used is rejected with HTTP `401`. `error_code` says why:

```json
{
  "success": false,
  "error": "invalid API key",
  "error_code": "invalid_api_key"
}
```

| `error_code`        | What to do                                                   |
| ------------------- | ------------------------------------------------------------ |
| `missing_api_key`   | Send the key in the `X-API-Key` header.                      |
| `invalid_api_key`   | Check for typos, or copy the key again from the dashboard.   |
| `api_key_inactive`  | The key was turned off, or its package expired or ran out.   |
| `account_suspended` | [Contact support](/docs/support).                            |
| `auth_error`        | We couldn't check the key. Retry.                            |

## Keep your key secret [#keep-your-key-secret]

Anyone with your key can spend your balance.

<Callout type="warn" title="Only use your key on a server">
  Never put it in a browser, a mobile app, or a public repository. Load it from an environment
  variable or a secrets manager.
</Callout>

If a key leaks, click **Rotate key** in [Dashboard → API keys](https://peak.fo/dashboard/keys). You can rotate a key once an hour. The old key stops working within a few seconds.
