# Authentication and API keys

> The API key format, how to send a key, spending limits and reset windows, expiry, disabling and archiving keys, and storing them safely.

Every request to the Lykia gateway authenticates with an API key. A key belongs to a single project, and it decides which project the request is logged under, who pays for it and which limits apply.

## Sending the key

Send the key in the `Authorization` header using the `Bearer` scheme:

```http
Authorization: Bearer <LYKIA_API_KEY>
```

This applies to every endpoint under `https://api.getlykia.com/v1`. The OpenAI SDK and OpenAI-compatible libraries build the header for you from their `api_key` / `apiKey` setting.

To confirm a key works and see its limits, call [`GET /key`](https://www.getlykia.com/en/docs/api-reference/key):

**Request**

cURL

```bash
curl https://api.getlykia.com/v1/key \
  -H "Authorization: Bearer $LYKIA_API_KEY"
```

Python

```python
import os

import requests

response = requests.get(
    "https://api.getlykia.com/v1/key",
    headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
    timeout=30,
)
if response.status_code == 401:
    raise SystemExit("The key is missing, invalid, disabled or expired.")
response.raise_for_status()
print(response.json()["data"])
```

TypeScript

```typescript
const response = await fetch("https://api.getlykia.com/v1/key", {
  headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}` },
});
if (response.status === 401) {
  throw new Error("The key is missing, invalid, disabled or expired.");
}
if (!response.ok) {
  throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);
}

const { data } = await response.json();
console.log(data);
```

Go

```go
package main

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

func main() {
	req, err := http.NewRequest(http.MethodGet, "https://api.getlykia.com/v1/key", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LYKIA_API_KEY"))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode == http.StatusUnauthorized {
		panic("the key is missing, invalid, disabled or expired")
	}
	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("Lykia returned %d: %s", resp.StatusCode, body))
	}
	fmt.Println(string(body))
}
```

**Response (200)**

```json
{
  "data": {
    "label": "lyk-v1-3f9a…c41e",
    "limit": 50,
    "limit_reset": "monthly",
    "usage": 18.47172,
    "limit_remaining": 31.52828,
    "company": {
      "id": "6b0472819bcb6b3a1239379b",
      "name": "Acme Products"
    },
    "project": {
      "id": "6b0472819bcb6b3a1239379d",
      "name": "Support bot"
    }
  }
}
```

If the key is missing, unknown, disabled, archived or expired, or its company is suspended, you get `401` (a key whose project has been archived gets `403` with the code `project_archived`):

```json
{
  "error": {
    "message": "Invalid API key",
    "type": "authentication_error",
    "code": "invalid_api_key",
    "status": 401,
    "metadata": {
      "reason": "unauthorized"
    }
  }
}
```

## Key format

API keys start with the prefix `lyk-v1-`, followed by 64 hexadecimal characters:

```text
lyk-v1-<64 hexadecimal characters>
```

The prefix makes keys easy to spot for code reviewers and secret scanners. The dashboard and logs only ever show a masked label, such as `lyk-v1-3f9a…c41e`, never the full key.

## A key is shown once

The full key is displayed once, at the moment you create it. Lykia stores only an HMAC-SHA256 hash of the key, computed with a secret held on the server, plus the masked label; it has no way of showing you the key again. If you lose a key, create a new one and archive the old one.

> **Tip:** Paste a full key into the search box of the dashboard's key list to find out which entry it belongs to. Lykia hashes what you paste and matches it.

## Who manages keys

Keys are created and edited under **API keys** in a project. The company owner, managers and project managers assigned to that project can do this. Each key has a name and an owner (the person who created it). Name keys after what they are for, like `backend-prod` or `nightly-batch`, and the logs will tell you which one did what.

## Spending limits and reset windows

You can give each key a spending limit in USD. Leave it empty and the key has no limit of its own (the company balance and the project budget still apply).

You also choose when the limit resets:

| Reset   | Meaning                                                    |
| ------- | ---------------------------------------------------------- |
| None    | The limit covers the key's whole lifetime.                 |
| Daily   | Starts over every day at 00\:00 UTC.                       |
| Weekly  | Starts over every Monday at 00\:00 UTC.                    |
| Monthly | Starts over on the first day of every month at 00\:00 UTC. |

Once spending in the current window reaches the limit, requests with that key return `402` until the next window begins. Before sending a request, Lykia reserves its maximum cost against the limit, so requests in flight cannot take a key past its limit; a request that what is left cannot cover is rejected with `402` early (see [Limits](https://www.getlykia.com/en/docs/guides/limits#key-spending-limit)).

By default only spending paid with credits counts toward the limit. If your project uses its own provider keys, a setting on the API key lets you count the list-price equivalent of those requests as well.

The `usage` and `limit_remaining` fields of `GET /key` show what has been spent in the current window and how much is left.

## Expiry

A key can have an expiry date. After that date, requests with the key return `401`. When you hand out temporary access (a demo, a contractor, a time-boxed trial), setting an expiry date at creation means you cannot forget to turn the key off.

## Disabling and archiving

Keys are never deleted. A key is in one of three states:

- **Active**: accepts requests.
- **Disabled**: requests are rejected with `401`. You can re-enable the key whenever you like.
- **Archived**: requests are rejected with `401` and the key can never be enabled again. Its logs and usage history are kept.

A status change reaches the gateway within a few seconds. If you suspect a key has leaked, disable it first, then create a replacement and roll it out, and finally archive the old key.

When a project is archived, all of its keys are rejected with `403` (code `project_archived`), and no new keys can be created in it.

The dashboard shows when each key was last used. That timestamp is updated at most once a minute.

## Keeping keys safe

- Keep keys out of source code. Read them from an environment variable (like `LYKIA_API_KEY` in the examples) or from a secrets manager.
- Never ship a key inside browser code, a mobile app or a desktop app: anything in those environments can be read by the user. Send requests through your own server.
- Use a separate key for each application and environment. Disabling one key then affects only that application, and you can follow spending per key.
- Use spending limits and expiry dates to keep the blast radius small.
- If a key ends up in a repository or a log by mistake, disable it straight away and replace it.

## Related

- [Projects](https://www.getlykia.com/en/docs/guides/projects): the project a key belongs to, and project budgets.
- [Limits](https://www.getlykia.com/en/docs/guides/limits): how key limits, project budgets and rate limits work together.
- [`GET /key`](https://www.getlykia.com/en/docs/api-reference/key): every field of the key information.
