# Power Boys Developer API (v1)

Reference for the Power Boys bot API at https://powerboys.noxiaz.dk. It is written so that both people and AI coding
assistants can implement a client from this page alone.

With a personal API token you can:

- list your bots and the game modes,
- upload a new version of a bot, or create a bot,
- choose which game modes a bot plays,
- read, replace and delete a bot's `settings.json`,
- download, upload and delete the `data.json` a bot saves between games,
- read a bot's game history (score, win, place, settings and every participant of each game), per game mode.

A token only reaches the endpoints on this page and only your own bots. It cannot change your password, profile or tokens.

## Authentication

1. Log in at https://powerboys.noxiaz.dk and open **Profile → API Access** (`/profile?section=api`).
2. Name the token and press **Generate**. The token starts with `pb_` and is shown once. You can hold up to 10 tokens and
   revoke any of them.
3. Send it as a Bearer token with every request:

```http
Authorization: Bearer pb_your_token_here
```

A missing, revoked or mistyped token gives `401`. Keep the token in an environment variable or CI secret
(for example `POWERBOYS_TOKEN`), never in a bot's source code.

## Conventions

- **Base URL:** `https://powerboys.noxiaz.dk/api/v1`
- **JSON:** request and response bodies are JSON with camelCase property names. Dates are ISO 8601 with an offset,
  for example `2026-11-20T14:03:11.123+00:00`.
- **Bot ids:** every `{botId}` is the id of one of your bots, from `GET /api/v1/bots`. Bot ids never change.
- **Game modes:** wherever the API takes a game mode (`{gameMode}` in a path, `gameMode` in a query, entries of
  `gameModes` in a body) you can pass its numeric id or its name, for example `1` or `CheeseGame`. Names are not
  case-sensitive. `GET /api/v1/gamemodes` lists them.
- **Errors:** error responses have a plain-text body explaining what went wrong (see [Status codes](#status-codes)).
- **Interactive explorer:** the same endpoints are in the Swagger UI at https://powerboys.noxiaz.dk/help.

## Endpoints

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/api/v1/bots` | List your bots |
| GET | `/api/v1/gamemodes` | List game modes |
| PUT | `/api/v1/bots/{botId}/gamemodes` | Choose the bot's game modes |
| GET | `/api/v1/bots/{botId}/games` | Read the bot's game history |
| GET | `/api/v1/bots/{botId}/data` | List the bot's data files |
| GET | `/api/v1/bots/{botId}/data/{gameMode}` | Download data.json |
| PUT | `/api/v1/bots/{botId}/data/{gameMode}` | Upload data.json |
| DELETE | `/api/v1/bots/{botId}/data/{gameMode}` | Delete data.json |
| GET | `/api/v1/bots/{botId}/settings` | Download settings.json |
| PUT | `/api/v1/bots/{botId}/settings` | Change settings.json |
| DELETE | `/api/v1/bots/{botId}/settings` | Delete settings.json |
| PUT | `/api/v1/bots/{botId}/file` | Upload a new version of a bot |
| POST | `/api/v1/bots` | Create a new bot |

---

### GET /api/v1/bots

Lists your bots. Use it to find the bot id the other endpoints need.

Response `200`:

```json
[
  {
    "id": 42,
    "name": "Cheddar",
    "fileName": "bot.js",
    "victoryComment": "Too easy",
    "isPrimary": true,
    "md5Hash": "9e107d9d372bb6826bd81d3542a419d6",
    "uploadedDate": "2026-11-19T21:14:02+00:00",
    "gameModeIds": [1, 3],
    "data": [
      { "gameModeId": 1, "gameMode": "CheeseGame", "updatedDate": "2026-11-20T09:12:44+00:00", "size": 18342 }
    ]
  }
]
```

| Field | Meaning |
| --- | --- |
| `uploadedDate` | When the program file was last uploaded; `null` when unknown. |
| `gameModeIds` | The game modes the bot plays. |
| `data` | One entry per game mode that has a data.json. `size` is the length of the JSON text in characters. |

---

### GET /api/v1/gamemodes

Lists every game mode.

Response `200`:

```json
[
  { "id": 1, "name": "CheeseGame", "isActive": true },
  { "id": 2, "name": "TetrisGame", "isActive": true }
]
```

Only active game modes are played. A bot's choice for an inactive game mode is kept until it is active again.

---

### PUT /api/v1/bots/{botId}/gamemodes

Chooses which game modes the bot plays, from its next match.

Request body:

```json
{ "gameModes": ["CheeseGame", 3] }
```

- Each entry is a game mode name (string) or id (number).
- The bot plays exactly the listed active game modes; an empty list stops it in all active game modes.
- Its choice for inactive game modes is kept as it is.

Response `200`: the updated bot, in the same shape as an entry of `GET /api/v1/bots`.
`400` when the body has no `gameModes` list or names an unknown game mode.

---

### GET /api/v1/bots/{botId}/games

The bot's game history: the same games as the history bar on the Bots screen. Each game has the bot's score, whether it
won, its place, the game settings and every participant with their score. Games from before the bot's last stats reset
(the reset button on the Bots screen) are not included.

Query parameters (all optional):

| Parameter | Default | Meaning |
| --- | --- | --- |
| `gameMode` | all game modes | Only games of this game mode (id or name). |
| `limit` | `100` | Games per page, 1 to 1000. |
| `order` | `desc` | `desc` = newest first, `asc` = oldest first. |
| `beforeLobbyId` | none | Only games with a smaller `lobbyId` (page back through history with `order=desc`). |
| `afterLobbyId` | none | Only games with a larger `lobbyId` (fetch only new games with `order=asc`). |

Example: `GET /api/v1/bots/42/games?gameMode=CheeseGame&limit=2`

Response `200`:

```json
{
  "botId": 42,
  "gameModeId": 1,
  "gameMode": "CheeseGame",
  "summary": { "games": 57, "wins": 21, "losses": 36, "winRate": 0.3684, "averageScore": 74.2 },
  "games": [
    {
      "lobbyId": 18350,
      "createdDate": "2026-11-20T15:09:47+00:00",
      "gameModeId": 1,
      "gameMode": "CheeseGame",
      "settings": ["WrappingEdge"],
      "score": 120,
      "isWin": true,
      "rank": 1,
      "durationInMilliseconds": 61234,
      "participants": [
        { "userId": 7, "displayName": "Alice", "color": "#3bd6ff", "botId": 42, "botName": "Cheddar", "score": 120, "rank": 1, "teamId": null },
        { "userId": 9, "displayName": "Bob", "color": "#ff5a5a", "botId": 51, "botName": "Gouda", "score": 80, "rank": 2, "teamId": null }
      ]
    },
    {
      "lobbyId": 18342,
      "createdDate": "2026-11-20T15:02:11+00:00",
      "gameModeId": 1,
      "gameMode": "CheeseGame",
      "settings": [],
      "score": 40,
      "isWin": false,
      "rank": 3,
      "durationInMilliseconds": 60011,
      "participants": [
        { "userId": 9, "displayName": "Bob", "color": "#ff5a5a", "botId": 51, "botName": "Gouda", "score": 130, "rank": 1, "teamId": null },
        { "userId": 12, "displayName": "Cara", "color": "#9dff5a", "botId": 63, "botName": "Brie", "score": 95, "rank": 2, "teamId": null },
        { "userId": 7, "displayName": "Alice", "color": "#3bd6ff", "botId": 42, "botName": "Cheddar", "score": 40, "rank": 3, "teamId": null }
      ]
    }
  ],
  "hasMore": true
}
```

| Field | Meaning |
| --- | --- |
| `gameModeId`, `gameMode` (top level) | The game mode filter; `null` when the history covers all game modes. |
| `summary` | Totals over **every** game matching `gameMode`, not just this page. `winRate` is from 0 to 1. |
| `lobbyId` | The game id. Higher is newer. The replay is at `https://powerboys.noxiaz.dk/replay/{lobbyId}`. |
| `settings` | Game settings the game was played with, for example `WrappingEdge`. Empty when the game used the defaults. |
| `score` | The bot's score in the game. |
| `isWin` | `true` when `score` is 100 or more, the same rule as the Bots screen. |
| `rank` | The bot's place, 1 for the highest score. Equal scores share a place. |
| `durationInMilliseconds` | How long the game ran; `null` when unknown. |
| `participants` | Every bot in the game, ordered by place, including your own (match on `botId`). |
| `hasMore` | `true` when more games match beyond this page in the requested direction. |

Paging recipes:

- **Newest games:** `GET /api/v1/bots/42/games?gameMode=CheeseGame`
- **Older pages:** repeat with `beforeLobbyId` = the smallest `lobbyId` of the previous page, while `hasMore` is `true`.
- **Only new games since last time:** store the largest `lobbyId` you have seen, then call
  `?order=asc&afterLobbyId={stored}` and repeat with the new largest `lobbyId` while `hasMore` is `true`.

`404` when the bot is not yours or the game mode does not exist. `400` when `limit` or `order` is invalid.

---

### GET /api/v1/bots/{botId}/data

Lists the bot's data.json files: the same `data` list as in `GET /api/v1/bots`, for one bot. An empty list means the bot
has not saved any data yet.

---

### GET /api/v1/bots/{botId}/data/{gameMode}

Downloads the raw data.json for one game mode, exactly what the bot will see in its next game in that mode.
`404` when the bot has no data for that game mode yet.

---

### PUT /api/v1/bots/{botId}/data/{gameMode}

Replaces the data.json for one game mode; the bot sees it from its next game.

- Send the JSON as the request body with `Content-Type: application/json`, or as a `multipart/form-data` field named `file`.
- It must use the [data.json format](#the-datajson-format). A missing section becomes empty.
- At most 10 MB minified (`413` when larger).

Response `200`: `{ "gameModeId": 1, "gameMode": "CheeseGame", "updatedDate": "...", "size": 18342 }`.
`409` when a game saved the same data.json at the same moment; try again.

---

### DELETE /api/v1/bots/{botId}/data/{gameMode}

Deletes the data.json for one game mode, so the bot's next game in that mode starts without data.
Response `204`, also when there was nothing to delete.

---

### GET /api/v1/bots/{botId}/settings

Downloads the bot's settings.json exactly as stored. The server places it next to the bot in every game.
`404` when the bot has no settings.

---

### PUT /api/v1/bots/{botId}/settings

Replaces the bot's settings.json; the bot reads it from its next game. Send any valid JSON as the request body with
`Content-Type: application/json`, or as a `multipart/form-data` field named `file`. Response `204`.
`400` when the body is not valid JSON.

---

### DELETE /api/v1/bots/{botId}/settings

Removes the bot's settings.json. Response `204`, also when the bot had no settings.

---

### PUT /api/v1/bots/{botId}/file

Uploads a new version of an existing bot. `multipart/form-data` with:

| Field | Required | Meaning |
| --- | --- | --- |
| `file` | yes | The bot program: a `.js` file, or an `.exe` if your account has the C# role. File name at most 50 characters. |
| `settings` | no | settings.json text that replaces the bot's settings. Left out = keep the current settings. |

Scores, cosmetics and data.json are kept. Response `200`: the updated bot. `502` when the file could not be stored.

---

### POST /api/v1/bots

Creates a new bot. `multipart/form-data` with:

| Field | Required | Meaning |
| --- | --- | --- |
| `file` | yes | The bot program (`.js`, or `.exe` with the C# role). |
| `name` | no | Bot name, at most 50 characters. Defaults to the file name without extension. |
| `victoryComment` | no | At most 50 characters. |
| `settings` | no | settings.json text. |

The new bot plays all game modes. Response `200`: the created bot. `409` when all 3 bot slots are used.
Customize its look on the Bots screen afterwards.

## The data.json format

Each bot has one data.json per game mode (up to 10 MB). Before every game the server places it next to the bot, beside
settings.json. During and right after a game the bot changes it with the `UpdateData` call from the game library.

```json
{
  "games": {
    "18342": { "added": "2026-11-13T15:02:11+00:00", "data": { "route": [3, 7, 12] } },
    "18350": { "added": "2026-11-13T15:09:47+00:00", "data": "plain text is stored as a JSON string" }
  },
  "values":   { "strategy": "aggressive", "weights": { "cheese": 1.5, "enemy": -0.8 } },
  "counters": { "gamesPlayed": 57, "wins": 21 }
}
```

- `games`: one entry per game, keyed by the game id (`lobbyId`). When the file would pass 10 MB the oldest entries are deleted.
- `values`: values set or removed per key. When games run at the same time, the last game to finish wins that key.
- `counters`: numbers. Increments from games running at the same time are added together.

## Status codes

| Code | Meaning |
| --- | --- |
| 200 | Success. JSON body (or the data.json / settings.json file). |
| 204 | Success with no body: settings changed, or data or settings deleted. |
| 400 | Invalid request: missing file or body, wrong file type, name too long, settings not valid JSON, data.json not in the data.json format, unknown game mode in `gameModes`, or invalid `limit` / `order`. |
| 401 | Missing, revoked or mistyped token. |
| 404 | The bot is not yours or does not exist, the game mode does not exist, or there is no data or settings yet. |
| 409 | All bot slots are in use (create), or a game saved the same data.json while you uploaded it. Try again. |
| 413 | The uploaded data.json is larger than 10 MB. |
| 502 | The bot file could not be stored. Try again. |

## Examples

### curl

```bash
TOKEN="pb_your_token_here"
BASE="https://powerboys.noxiaz.dk"

# Find your bot ids
curl -fsS -H "Authorization: Bearer $TOKEN" "$BASE/api/v1/bots"

# Last 50 CheeseGame games of bot 42, with win/loss summary
curl -fsS -H "Authorization: Bearer $TOKEN" "$BASE/api/v1/bots/42/games?gameMode=CheeseGame&limit=50"

# Upload a new version of bot 42
curl -fsS -X PUT -H "Authorization: Bearer $TOKEN" -F "file=@dist/bot.js" "$BASE/api/v1/bots/42/file"

# Download, upload or delete its CheeseGame data.json
curl -fsS -H "Authorization: Bearer $TOKEN" -o data.json "$BASE/api/v1/bots/42/data/CheeseGame"
curl -fsS -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  --data-binary @data.json "$BASE/api/v1/bots/42/data/CheeseGame"
curl -fsS -X DELETE -H "Authorization: Bearer $TOKEN" "$BASE/api/v1/bots/42/data/CheeseGame"

# Read and change its settings.json
curl -fsS -H "Authorization: Bearer $TOKEN" "$BASE/api/v1/bots/42/settings"
curl -fsS -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  --data-binary @settings.json "$BASE/api/v1/bots/42/settings"

# Play only CheeseGame and TetrisGame
curl -fsS -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{ "gameModes": ["CheeseGame", "TetrisGame"] }' "$BASE/api/v1/bots/42/gamemodes"
```

### TypeScript (Node 18+)

```ts
const BASE = "https://powerboys.noxiaz.dk";
const headers = { Authorization: `Bearer ${process.env.POWERBOYS_TOKEN}` };

type Participant = { userId: number; displayName: string; color: string; botId: number; botName: string; score: number; rank: number; teamId: number | null };
type Game = { lobbyId: number; createdDate: string; gameModeId: number | null; gameMode: string; settings: string[]; score: number; isWin: boolean; rank: number; durationInMilliseconds: number | null; participants: Participant[] };
type GamesPage = { botId: number; gameModeId: number | null; gameMode: string | null; summary: { games: number; wins: number; losses: number; winRate: number; averageScore: number }; games: Game[]; hasMore: boolean };

/** Every game of a bot in one game mode that is newer than afterLobbyId, oldest first. */
export async function fetchNewGames(botId: number, gameMode: string, afterLobbyId = 0): Promise<Game[]> {
  const games: Game[] = [];
  let cursor = afterLobbyId;
  for (;;) {
    const url = `${BASE}/api/v1/bots/${botId}/games?gameMode=${encodeURIComponent(gameMode)}&order=asc&limit=1000&afterLobbyId=${cursor}`;
    const res = await fetch(url, { headers });
    if (!res.ok) throw new Error(`History failed: ${res.status} ${await res.text()}`);
    const page = (await res.json()) as GamesPage;
    games.push(...page.games);
    if (!page.hasMore || page.games.length === 0) return games;
    cursor = page.games[page.games.length - 1].lobbyId;
  }
}
```

### PowerShell 7

```powershell
$base    = "https://powerboys.noxiaz.dk"
$headers = @{ Authorization = "Bearer $env:POWERBOYS_TOKEN" }

# Win rate of bot 42 in CheeseGame, and its last 10 games
$page = Invoke-RestMethod "$base/api/v1/bots/42/games?gameMode=CheeseGame&limit=10" -Headers $headers
$page.summary
$page.games | Select-Object lobbyId, createdDate, score, isWin, rank
```
