> ## Documentation Index
> Fetch the complete documentation index at: https://developers.scoutworks.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Check-in at the door

> Print a QR card for each young person, then scan them in as they arrive. Each scan marks them present on tonight’s register.

Taking a register by hand at the start of a busy evening is easy to skip. This recipe turns it into a scan at the door: each young person has a card with a QR code, a laptop or tablet by the door scans it, and Scoutworks marks them **present** on tonight’s register.

It has two parts. **Print the cards** once a term. **Run the kiosk** each evening. Both use Python 3.9 or later. Printing also uses the `qrcode` package: `pip install requests qrcode`.

The scanner can be any barcode scanner that types what it reads, the way a keyboard does. Most USB and Bluetooth scanners work like this, and so do “scan to keyboard” apps on a phone or tablet.

## 1. Print the cards

This script writes `cards.html`: one card for each young person in a section, with their name and a QR code. Open it in a browser and print it on card.

```python cards.py theme={null}
import html
import io
import os
import time

import qrcode
import qrcode.image.svg
import requests

# The section to print. Get its id from GET /sections.
SECTION_ID = os.environ.get("SECTION_ID", "")

BASE = "https://api-demo.scoutworks.app/api/v1"
API_KEY = os.environ.get(
    "SCOUTWORKS_API_KEY",
    "sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab",
)
session = requests.Session()
session.headers["Authorization"] = f"Bearer {API_KEY}"


def read_all(path, **filters):
    """Every item in a list, following nextCursor to the last page."""
    items, params = [], {"limit": 200, **filters}
    while True:
        res = session.get(BASE + path, params=params, timeout=30)
        if res.status_code == 429:
            time.sleep(res.json().get("retryAfter", 30))
            continue
        res.raise_for_status()
        page = res.json()
        items += page["data"]
        if page["nextCursor"] is None:
            return items
        params["cursor"] = page["nextCursor"]


def qr_svg(text):
    out = io.BytesIO()
    qrcode.make(text, image_factory=qrcode.image.svg.SvgPathImage).save(out)
    return out.getvalue().decode()


filters = {"sectionId": SECTION_ID} if SECTION_ID else {}
members = sorted(
    read_all("/members", **filters), key=lambda m: (m["lastName"], m["firstName"])
)
cards = "".join(
    f'<div class="card">{qr_svg(m["id"])}<p>{html.escape(m["firstName"])} '
    f'{html.escape(m["lastName"])}</p></div>'
    for m in members
)
with open("cards.html", "w", encoding="utf-8") as f:
    f.write(
        "<!doctype html><meta charset=utf-8><title>Check-in cards</title>"
        "<style>body{font-family:sans-serif}.card{display:inline-block;width:5cm;"
        "margin:.3cm;padding:.3cm;border:1px dashed #999;text-align:center}"
        ".card svg{width:4cm;height:4cm}</style>" + cards
    )
print(f"Saved cards.html with {len(members)} cards")
```

Run it with the [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) to see what the cards look like:

```bash theme={null}
python cards.py
```

The QR code holds the young person’s Scoutworks id and nothing else, so a lost card tells nobody who it belongs to. Print new cards when someone joins.

## 2. Run the kiosk

This script asks which of today’s meetings to take the register for, then waits for scans. It sends them to Scoutworks in batches: when 20 are waiting, or with the next scan once 15 seconds have passed. Press Enter on its own to send what is waiting. A slow connection never holds up the queue at the door. A scan that cannot be sent waits in `checkin-queue.json` and goes with the next batch, even if the script is stopped and started again.

```python kiosk.py theme={null}
import datetime
import json
import os
import time
import uuid

import requests

BASE = "https://api.scoutworks.app/api/v1"
API_KEY = os.environ["SCOUTWORKS_API_KEY"]
QUEUE_FILE = "checkin-queue.json"
BATCH_SIZE, BATCH_SECONDS = 20, 15

session = requests.Session()
session.headers["Authorization"] = f"Bearer {API_KEY}"


def load_queue():
    try:
        with open(QUEUE_FILE, encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return []


def save_queue(queue):
    with open(QUEUE_FILE, "w", encoding="utf-8") as f:
        json.dump(queue, f)


def send(queue):
    """Sends up to BATCH_SIZE scans. Keeps any that could not be sent."""
    batch = queue[:BATCH_SIZE]
    try:
        res = session.post(
            BASE + "/attendance/bulk",
            json={"items": batch},
            # A new key for each batch: two copies sent at once cannot both run.
            headers={"Idempotency-Key": str(uuid.uuid4())},
            timeout=30,
        )
    except requests.RequestException:
        print("  Offline. The scans will go with the next batch.")
        return queue
    if res.status_code in (409, 429) or res.status_code >= 500:
        print("  Scoutworks is busy. The scans will go with the next batch.")
        return queue
    if not res.ok:
        error = res.json()["error"]
        raise SystemExit(f"{res.status_code} {error['code']}: {error['message']}")
    for result in res.json()["data"]:
        if result["status"] == "error":
            print(f"  Not marked: {result['error']['message']}")
    return queue[len(batch):]


# Pick tonight's meeting.
today = datetime.date.today()
res = session.get(
    BASE + "/events",
    params={"from": f"{today}T00:00:00Z", "to": f"{today + datetime.timedelta(days=1)}T00:00:00Z"},
    timeout=30,
)
res.raise_for_status()
events = res.json()["data"]
if not events:
    raise SystemExit("No published event today.")
for n, event in enumerate(events, 1):
    print(f"{n}. {event['title']} at {event['startsAt'][11:16]} UTC")
event = events[int(input("Which one? ")) - 1] if len(events) > 1 else events[0]
print(f"Scanning in for {event['title']}. Press Ctrl+C to finish.")

queue, last_sent = load_queue(), time.monotonic()
try:
    while True:
        scan = input().strip()
        if scan:
            queue.append({"eventId": event["id"], "memberId": scan, "attendance": "present"})
            save_queue(queue)
            print(f"  Got it ({len(queue)} waiting)")
        if queue and (len(queue) >= BATCH_SIZE or time.monotonic() - last_sent > BATCH_SECONDS):
            queue = send(queue)
            save_queue(queue)
            last_sent = time.monotonic()
except KeyboardInterrupt:
    while queue:
        before = len(queue)
        queue = send(queue)
        save_queue(queue)
        if len(queue) == before:
            raise SystemExit(f"{len(queue)} scans are still waiting in {QUEUE_FILE}. Run the kiosk again to send them.")
    print("All scans sent.")
```

## 3. Use your own key

The sandbox key is read-only, so the kiosk needs your own key. A group admin creates one in **Settings → Integrations → API keys**, with these scopes:

* `members:read`, to print the cards;
* `events:read`, to find tonight’s meeting;
* `attendance:read` and `attendance:write`, to mark the register.

Change `api-demo.scoutworks.app` to `api.scoutworks.app` in `cards.py`, and set your key in the environment. `read -s` asks for it without showing it:

```bash theme={null}
read -rs -p "Scoutworks API key: " SCOUTWORKS_API_KEY && export SCOUTWORKS_API_KEY
python kiosk.py
```

**Try it with one card first.** Scan one young person, press Ctrl+C, and check tonight’s register in Scoutworks. They should be marked present. If the mark is wrong, change it in Scoutworks, which is also where you take a mark off.

## Notes

* **Only present.** The kiosk marks who came. Mark anyone who did not come as absent in Scoutworks, or send `"attendance": "absent"` for them.
* **Scanning twice is fine.** The same scan again answers `unchanged`. A batch counts as one write against the limit of 30 a minute, so a queue of arrivals never reaches it. See [Writing data](https://developers.scoutworks.app/guides/writing-data.md#write-many-records-at-once-bulk-writes).
* **Families are not told.** A mark never emails or notifies a parent, and never changes their reply to the event.
* **Joint events.** A young person from another group is refused: each group marks its own. A meeting that is full refuses a walk-in, because the kiosk cannot ask a leader to confirm. Mark that young person in Scoutworks, which can go over the limit.
* **A webhook.** If your group has a webhook for `attendance.recorded`, each batch sends one event for the register, not one for each young person.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.