# Your first call in five minutes

> Ask the sandbox for a code for a table device and read GET /device with its token. With Python, JavaScript, C#, PHP, Go, Java, curl and for the ESP32.

You need a terminal, and the Arduino IDE for the ESP32. You do not need a packeroo account in the sandbox: a device asks for its code without signing in and confirms it there itself. The language you pick here holds for every example on this page, in the guide and in the reference. PowerShell, Ruby, Kotlin, Swift, Dart and Rust are in the [reference](https://developers.packeroo.com/en/reference/).

## 1. Ask for a code

Send `POST /device-pairings` to the sandbox. Two headers are required: `User-Agent` names your device with product and firmware, and `Idempotency-Key` is a UUID or ULID you make new for this request.

Python:

```python
import json, urllib.request, uuid

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/device-pairings",
    method="POST",
    data=json.dumps({"model": "Kickertisch-Beispiel", "firmware": "1.0"}).encode(),
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Idempotency-Key": str(uuid.uuid4()),
        "Content-Type": "application/json",
        "Accept-Language": "en",
    },
)
with urllib.request.urlopen(request) as response:
    print(json.load(response)["data"])
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/device-pairings', {
  method: 'POST',
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    'Idempotency-Key': crypto.randomUUID(),
    'Content-Type': 'application/json',
    'Accept-Language': 'en',
  },
  body: JSON.stringify({ model: 'Kickertisch-Beispiel', firmware: '1.0' }),
})
console.log(response.status, (await response.json()).data)
```

C#:

```csharp
using System.Net.Http.Json;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.qm.packeroo.com/api/v1/device-pairings")
{
    Content = JsonContent.Create(new { model = "Kickertisch-Beispiel", firmware = "1.0" }),
};
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
request.Headers.AcceptLanguage.ParseAdd("en");
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$bytes = random_bytes(16);
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
$key = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));

$curl = curl_init('https://api.qm.packeroo.com/api/v1/device-pairings');
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => ["Idempotency-Key: $key", 'Content-Type: application/json', 'Accept-Language: en'],
    CURLOPT_POSTFIELDS => json_encode(['model' => 'Kickertisch-Beispiel', 'firmware' => '1.0']),
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
package main

import (
	"bytes"
	"crypto/rand"
	"fmt"
	"io"
	"net/http"
)

func main() {
	b := make([]byte, 16)
	_, _ = rand.Read(b)
	b[6], b[8] = b[6]&0x0f|0x40, b[8]&0x3f|0x80
	key := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

	body := bytes.NewBufferString(`{"model": "Kickertisch-Beispiel", "firmware": "1.0"}`)
	request, _ := http.NewRequest("POST", "https://api.qm.packeroo.com/api/v1/device-pairings", body)
	request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
	request.Header.Set("Idempotency-Key", key)
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Accept-Language", "en")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	data, _ := io.ReadAll(response.Body)
	fmt.Println(response.Status, string(data))
}
```

Java:

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;

public class AskForCode {
    public static void main(String[] args) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/device-pairings"))
            .header("User-Agent", "Kickertisch-Beispiel/1.0")
            .header("Idempotency-Key", UUID.randomUUID().toString())
            .header("Content-Type", "application/json")
            .header("Accept-Language", "en")
            .POST(HttpRequest.BodyPublishers.ofString("{\"model\": \"Kickertisch-Beispiel\", \"firmware\": \"1.0\"}"))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

curl:

```bash
# uuidgen exists on macOS and many Linux systems; otherwise the kernel hands out a UUID.
KEY="$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)"
curl -sS -X POST https://api.qm.packeroo.com/api/v1/device-pairings \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Idempotency-Key: $KEY" \
  -H "Content-Type: application/json" \
  -H "Accept-Language: en" \
  -d '{"model": "Kickertisch-Beispiel", "firmware": "1.0"}'
```

ESP32:

```cpp
// In setup(), after Wi-Fi, configTime() and tls.setCACert() as in the full sketch of the guide.
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/device-pairings");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Idempotency-Key", newKey());  // newKey() from the full sketch
http.addHeader("Content-Type", "application/json");
http.addHeader("Accept-Language", "en");
int status = http.POST("{\"model\":\"Kickertisch-ESP32\",\"firmware\":\"1.0\"}");
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

The answer comes with `201 Created`:

```json
{
  "data": {
    "code": "K7F4QX",
    "expires_at": "2026-11-22T14:15:00Z",
    "token": "pkd_test_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD"
  }
}
```

You see the token only this once. Put it into an environment variable in the same terminal; the examples of the next steps read it from there:

```bash
export PACKEROO_TOKEN='pkd_test_…'   # your token from the answer here
# PowerShell: $env:PACKEROO_TOKEN = 'pkd_test_…'
```

On the ESP32 the sketch keeps it in the variable `token`.

## 2. Ask with the token

Ask `GET /device` with the token. Until someone has entered the code, the API answers `401` with the code `unauthenticated`: the token counts only once the code belongs to a table. With a wrong token, or a `pkd_test_` token against the live API, the answer looks the same. Step 3 shows whether your token is right.

Python:

```python
import json, os, urllib.error, urllib.request

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/device",
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Authorization": "Bearer " + os.environ["PACKEROO_TOKEN"],
    },
)
try:
    with urllib.request.urlopen(request) as response:
        print(response.status, json.load(response)["data"])
except urllib.error.HTTPError as error:
    print(error.code, error.read().decode())
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/device', {
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    Authorization: `Bearer ${process.env.PACKEROO_TOKEN}`,
  },
})
console.log(response.status, await response.json())
```

C#:

```csharp
using System.Net.Http.Headers;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.qm.packeroo.com/api/v1/device");
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
var token = Environment.GetEnvironmentVariable("PACKEROO_TOKEN");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$curl = curl_init('https://api.qm.packeroo.com/api/v1/device');
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('PACKEROO_TOKEN')],
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
request, _ := http.NewRequest("GET", "https://api.qm.packeroo.com/api/v1/device", nil)
request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
request.Header.Set("Authorization", "Bearer "+os.Getenv("PACKEROO_TOKEN"))
response, err := http.DefaultClient.Do(request)
if err != nil {
	panic(err)
}
defer response.Body.Close()
data, _ := io.ReadAll(response.Body)
fmt.Println(response.Status, string(data))
```

Java:

```java
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/device"))
    .header("User-Agent", "Kickertisch-Beispiel/1.0")
    .header("Authorization", "Bearer " + System.getenv("PACKEROO_TOKEN"))
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
```

curl:

```bash
curl -sS https://api.qm.packeroo.com/api/v1/device \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Authorization: Bearer $PACKEROO_TOKEN"
```

ESP32:

```cpp
// token: from the answer to step 1, as in the complete sketch.
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/device");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Authorization", "Bearer " + token);
int status = http.GET();
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

## 3. Have the code entered

Live, someone enters the code in the app, under Profile › Organization › Tables, then "Pair a device" at the table. In the sandbox no person is needed: your device confirms its code itself with `POST /sandbox/device-pairings/confirm` and the same token. It gets a test table of its own. If this answers `401`, no code waits for the token: it is wrong, or the code ran out after 10 minutes. Then start again at step 1.

Python:

```python
import json, os, urllib.error, urllib.request, uuid

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm",
    method="POST",
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Idempotency-Key": str(uuid.uuid4()),
        "Authorization": "Bearer " + os.environ["PACKEROO_TOKEN"],
    },
)
try:
    with urllib.request.urlopen(request) as response:
        print(response.status, json.load(response)["data"])
except urllib.error.HTTPError as error:
    print(error.code, error.read().decode())
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm', {
  method: 'POST',
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    'Idempotency-Key': crypto.randomUUID(),
    Authorization: `Bearer ${process.env.PACKEROO_TOKEN}`,
  },
})
console.log(response.status, await response.json())
```

C#:

```csharp
using System.Net.Http.Headers;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm");
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
var token = Environment.GetEnvironmentVariable("PACKEROO_TOKEN");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$curl = curl_init('https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm');
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => [
        'Idempotency-Key: ' . bin2hex(random_bytes(16)),
        'Authorization: Bearer ' . getenv('PACKEROO_TOKEN'),
    ],
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
request, _ := http.NewRequest("POST", "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm", nil)
request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
request.Header.Set("Idempotency-Key", key) // key: a new UUID, made as in step 1
request.Header.Set("Authorization", "Bearer "+os.Getenv("PACKEROO_TOKEN"))
response, err := http.DefaultClient.Do(request)
if err != nil {
	panic(err)
}
defer response.Body.Close()
data, _ := io.ReadAll(response.Body)
fmt.Println(response.Status, string(data))
```

Java:

```java
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm"))
    .header("User-Agent", "Kickertisch-Beispiel/1.0")
    .header("Idempotency-Key", UUID.randomUUID().toString())
    .header("Authorization", "Bearer " + System.getenv("PACKEROO_TOKEN"))
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
```

curl:

```bash
curl -sS -X POST https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" \
  -H "Authorization: Bearer $PACKEROO_TOKEN"
```

ESP32:

```cpp
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Idempotency-Key", newKey());
http.addHeader("Authorization", "Bearer " + token);
int status = http.POST("");
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

The answer is the device already, as `GET /device` shows it. This operation exists in the sandbox only; live it answers `404`, once `User-Agent` and `Idempotency-Key` are checked. The sandbox keeps the latest 100 test tables; the oldest is unpaired with its device when a new one comes.

Your device is paired now. From here on `GET /device` from step 2 answers `200`:

```json
{
  "data": {
    "id": "01JD7Q3V9TQ6Z8K2M4N5P6R7S8",
    "name": "Kickertisch Halle",
    "table": { "id": "01JD7Q2B1C3D4E5F6G7H8J9K0M", "name": "Tisch 2" },
    "location": { "id": "01JD7Q1A2B3C4D5E6F7G8H9J0K", "name": "Büro Freiburg", "time_zone": "Europe/Berlin" },
    "organization": { "id": "01JD7Q0Z9Y8X7W6V5T4S3R2Q1P", "name": "Beispiel AG" },
    "scopes": ["leagues:read", "standings:read", "matches:read", "matches:write", "matches:live"]
  }
}
```

The values above are an example. `scopes` names what the token may do later; the operations for it are [planned](https://developers.packeroo.com/en/concepts/#scopes).

## Next

- The [guide](https://developers.packeroo.com/en/guides/pair-a-table-device/) has the complete program, with waiting, an expired code and every error case.
- [Postman](https://developers.packeroo.com/en/downloads/#postman): import the collection, choose the environment "packeroo Sandbox", paste the token.
- The [reference](https://developers.packeroo.com/en/reference/) has every operation with code samples in many more languages.
