# TypeScript and Python clients

> One file for TypeScript or JavaScript, one for Python, with no dependencies. Copy it into your project: it runs every check, retries what is safe to retry, waits for asynchronous checks and verifies webhooks.

Base URL: `https://api.checksharecode.co.uk` · Auth: `authorization: Bearer <key>` · Web version: https://checksharecode.co.uk/docs/clients · Sign up: https://checksharecode.co.uk/signup?ref=md

## Get the file

Download into your project:

```bash
# TypeScript or JavaScript
curl -O https://checksharecode.co.uk/clients/checksharecode.ts

# Python
curl -O https://checksharecode.co.uk/clients/checksharecode.py
```

- **TypeScript or JavaScript:** [checksharecode.ts](https://checksharecode.co.uk/clients/checksharecode.ts) needs `fetch` and Web Crypto, so it runs on Node 20 or later, Deno, Bun, Cloudflare Workers and Supabase Edge Functions. Call it from your server: your API key must never reach a browser.
- **Python:** [checksharecode.py](https://checksharecode.co.uk/clients/checksharecode.py) uses only the standard library, Python 3.9 or later. Answers come back as dicts with the fields in the [API reference](https://checksharecode.co.uk/docs/api/check.md).
- It is your copy, under your version control: it changes only when you download it again. The date it was made is `CLIENT_VERSION` at the top.

> **Using a coding agent?** Ask it to download [checksharecode.ts](https://checksharecode.co.uk/clients/checksharecode.ts) or [checksharecode.py](https://checksharecode.co.uk/clients/checksharecode.py) into the project and use it for every call to the API.

## Run a check

Each check has a method: `rightToWork`, `rightToRent`, `immigrationStatus` and `drivingLicence` (in Python `right_to_work`, `right_to_rent`, `immigration_status` and `driving_licence`). They take the same fields as the endpoints and give back the same answer. A sandbox key (`rtw_test_`) gets the fixed test answers; a live key runs the real check.

TypeScript:

```ts
import { CheckShareCode, CheckShareCodeError } from "./checksharecode";

const csc = new CheckShareCode(process.env.CHECKSHARECODE_API_KEY);

const result = await csc.rightToWork({
  share_code: "AB1CD2EF3",
  date_of_birth: "1990-01-01",
  company_name: "Acme Ltd",
});
console.log(result.outcome, result.expiry_date);

try {
  const licence = await csc.drivingLicence({
    licence_number: "192GT2BD",
    check_code: "AAAA0001",
  });
  console.log(licence.points, licence.endorsements);
} catch (err) {
  if (!(err instanceof CheckShareCodeError)) throw err;
  // A check code works once: false means the same code can be sent again.
  if (err.checkCodeUsed !== false) console.log("Ask the driver for a new check code");
  console.log(err.code, err.message);
}
```

Python:

```python
import os
from checksharecode import CheckShareCode, CheckShareCodeError

csc = CheckShareCode(os.environ["CHECKSHARECODE_API_KEY"])

result = csc.right_to_work(
    share_code="AB1CD2EF3", date_of_birth="1990-01-01", company_name="Acme Ltd"
)
print(result["outcome"], result["expiry_date"])

try:
    licence = csc.driving_licence(
        licence_number="192GT2BD",
        check_code="AAAA0001",
    )
    print(licence["points"], licence["endorsements"])
except CheckShareCodeError as err:
    # A check code works once: False means the same code can be sent again.
    if err.check_code_used is not False:
        print("Ask the driver for a new check code")
    print(err.code, err.message)
```

A Northern Ireland licence number (8 digits) goes to the [Northern Ireland endpoint](https://checksharecode.co.uk/docs/api/driving-licence.md) without you choosing it. Every refusal is a `CheckShareCodeError` with the API’s `code`, `message`, HTTP `status`, `requestId` (quote it when you contact us) and the whole `error`, which has `upgrade_url` and the like when they apply.

## What it retries

| code | What the client does |
| --- | --- |
| BUSY | Waits the `Retry-After` seconds and sends it again. |
| TIMEOUT, INTERNAL | Sends it again after a few seconds. |
| RATE_LIMITED | Waits the `Retry-After` seconds and sends it again, when that is 30 seconds or less. |
| Driving licence | Sends the same code again only when `check_code_used` is `false` (or absent: the refusal came before the check). Never when it is `true` or `"unknown"`, because a code works once. |
| Anything else | Throws at once: the answer would be the same. So does an answer that isn’t the API’s JSON, such as a proxy’s error page, since it can’t say whether a licence code was used. |

It tries 3 times in all; set `maxAttempts` (`max_attempts` in Python) to change that, or to 1 to turn retries off. Each request times out after 60 seconds (`timeoutMs`, or `timeout` in seconds in Python), long enough for a live check. A request cut off by the network is not retried, since it may have run.

## Asynchronous checks

An [asynchronous check](https://checksharecode.co.uk/docs/api/check-async.md) answers at once and runs in the background. `startCheck` queues one with an `Idempotency-Key` it makes for you, so a retry never queues it twice, and `waitForCheck` polls until it has succeeded or failed.

TypeScript:

```ts
const queued = await csc.startCheck("right_to_rent", {
  share_code: "AB1CD2EF3",
  date_of_birth: "1990-01-01",
  checker_name: "Acme Lettings",
  checker_type: "agent",
}, { client_reference: "applicant-4411" });

// Wait here, or skip this and take the result from your webhook.
const done = await csc.waitForCheck(queued.id);
if (done.status === "succeeded") console.log(done.result);
else console.log(done.error?.code);
```

Python:

```python
queued = csc.start_check(
    "right_to_rent",
    {
        "share_code": "AB1CD2EF3",
        "date_of_birth": "1990-01-01",
        "checker_name": "Acme Lettings",
        "checker_type": "agent",
    },
    client_reference="applicant-4411",
)

# Wait here, or skip this and take the result from your webhook.
done = csc.wait_for_check(queued["id"])
print(done["result"] if done["status"] == "succeeded" else done["error"]["code"])
```

## Verify webhooks

`verifyWebhook` checks the [Standard Webhooks](https://checksharecode.co.uk/docs/webhooks.md) signature with your `whsec_` secret and returns the event, or throws `WebhookVerificationError` for a wrong signature or one more than 5 minutes old. Pass the raw body.

TypeScript (Express):

```ts
import express from "express";
import { verifyWebhook } from "./checksharecode";

const app = express();

// The signature covers the exact bytes we sent, so read the raw body.
app.post("/hooks/checks", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = await verifyWebhook(process.env.CHECKSHARECODE_WEBHOOK_SECRET, req.headers, req.body);
  } catch {
    return res.status(400).send("bad signature");
  }
  // Retries reuse webhook-id: skip an event you've already handled.
  if (event.type === "check.succeeded") console.log(event.data.result);
  res.sendStatus(204);
});
```

Python (Flask):

```python
import os
from flask import Flask, request
from checksharecode import WebhookVerificationError, verify_webhook

app = Flask(__name__)

@app.post("/hooks/checks")
def checks_webhook():
    # The signature covers the exact bytes we sent, so read the raw body.
    try:
        event = verify_webhook(
            os.environ["CHECKSHARECODE_WEBHOOK_SECRET"], request.headers, request.get_data()
        )
    except WebhookVerificationError:
        return "bad signature", 400
    # Retries reuse webhook-id: skip an event you've already handled.
    if event["type"] == "check.succeeded":
        print(event["data"]["result"])
    return "", 204
```

See also: [Quickstart](https://checksharecode.co.uk/docs/quickstart.md) · [POST /v1/check/right-to-work](https://checksharecode.co.uk/docs/api/right-to-work.md)
