# Quickstart

This walk-through creates a desk ticket with `curl`. It takes about five minutes. You need a
ConnectCloud account with the permission to create API keys (`tenant:token:generate`) and, for
the last step, `desk:write`.

> **No account yet?** Run the same requests against the [sandbox](/guides/sandbox): replace
> `https://api.mbcom.cloud/api/<module>/v1` with `https://developers.mbcom.cloud/sandbox/<module>` and use any key starting with `cck_`.

## 1. Create an API key

In the portal open **Einstellungen › Anmeldung & Sicherheit › API-Schlüssel** and create a key. Pick only the
permissions your integration needs (here: `desk:read` and `desk:write`) and an expiry (default
90 days, at most 365). The key (`cck_…`) is shown **once**: store it in your secret manager.

For integrations that should not depend on one person, an administrator creates a
**service account** instead (**Einstellungen › Benutzer & Zugriff › Service-Konten & API-Schlüssel**). See
[Authentication](/guides/authentication).

```bash
export CONNECTCLOUD_API_KEY='cck_…'
export CC='https://api.mbcom.cloud'
```

## 2. Exchange the key for an access token

API keys are never sent to the module APIs directly. Exchange the key for a short-lived access
token at HR:

```bash
curl -s -X POST "$CC/api/hr/v1/auth/token" \
  -H "Authorization: Bearer $CONNECTCLOUD_API_KEY"
```

```json
{
  "accessToken": "eyJhbGciOiJIUzI1NiIs…",
  "tokenType": "Bearer",
  "expiresIn": 900,
  "expiresAt": "2026-03-02T09:45:00Z"
}
```

The token is valid for 15 minutes for every ConnectCloud API.

```bash
export ACCESS_TOKEN='eyJhbGciOiJIUzI1NiIs…'
```

## 3. Look up the desk configuration

Spaces, types, statuses, priorities and fields are **tenant configuration**: never hard-code
them, read them once from the bootstrap document:

```bash
curl -s "$CC/api/desk/v1/bootstrap" -H "Authorization: Bearer $ACCESS_TOKEN"
```

Note the `id` or `key` of the space (`spaces[]`) and the type (`types[]`) you want to use.

## 4. Create a ticket

```bash
curl -s -X POST "$CC/api/desk/v1/items" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6c1f0a52-0d0e-4a43-9c55-8f6e1f2a0b7d" \
  --data '{
    "spaceId": "SUP",
    "typeId": "stoerung",
    "title": "VPN-Verbindung bricht ab",
    "description": "Seit heute morgen trennt der VPN-Client alle 5 Minuten."
  }'
```

The answer is the new item (`201`) with its `id`, its `number` and its `version`. Sending the
same request again with the same `Idempotency-Key` returns the same item with `200` instead of a
duplicate, so retries after a timeout are safe.

## 5. Next steps

- Change the ticket: [optimistic locking](/guides/idempotency-and-concurrency) with `version`.
- Page through tickets: [pagination and delta sync](/guides/pagination).
- Get notified when something changes: [webhooks](/guides/webhooks).
- Browse every endpoint: [Desk reference](/reference/desk).

## A minimal client

Most integrations only need a small wrapper that caches the token and exchanges the key again
shortly before it expires:

```python
import os, time, requests

BASE = "https://api.mbcom.cloud"
KEY = os.environ["CONNECTCLOUD_API_KEY"]
_token = {"value": None, "expires": 0}

def token():
    # exchange again one minute before expiry; there is no refresh token
    if time.time() > _token["expires"] - 60:
        r = requests.post(f"{BASE}/api/hr/v1/auth/token",
                          headers={"Authorization": f"Bearer {KEY}"}, timeout=10)
        r.raise_for_status()
        body = r.json()
        _token.update(value=body["accessToken"], expires=time.time() + body["expiresIn"])
    return _token["value"]

def api(method, path, **kw):
    r = requests.request(method, BASE + path, timeout=30,
                         headers={"Authorization": f"Bearer {token()}", **kw.pop("headers", {})}, **kw)
    if r.status_code == 429:
        time.sleep(int(r.headers.get("Retry-After", "1")))
        return api(method, path, **kw)
    r.raise_for_status()
    return r.json() if r.content else None

print(api("GET", "/api/desk/v1/items", params={"limit": 10})["items"])
```

```typescript
const BASE = "https://api.mbcom.cloud";
let cached = { token: "", expires: 0 };

async function token(): Promise<string> {
  if (Date.now() > cached.expires - 60_000) {
    const r = await fetch(`${BASE}/api/hr/v1/auth/token`, {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.CONNECTCLOUD_API_KEY}` },
    });
    if (!r.ok) throw new Error(`token exchange failed: ${r.status}`);
    const body = await r.json();
    cached = { token: body.accessToken, expires: Date.now() + body.expiresIn * 1000 };
  }
  return cached.token;
}

export async function api(path: string, init: RequestInit = {}) {
  const r = await fetch(BASE + path, {
    ...init,
    headers: { ...init.headers, Authorization: `Bearer ${await token()}` },
  });
  if (!r.ok) throw new Error(`${r.status}: ${(await r.json()).code}`);
  return r.status === 204 ? null : r.json();
}
```
