# Create codes in bulk from a template

Use this when you already have a batch template and want your system to generate sub-codes for a list of devices, people or materials.

## Prerequisites

- A [personal API key](https://cli.im/open-api/en/openapi/v2/auth.md#create-key) with Read/write or Full permission. Organization keys cannot call these endpoints.
- The member who owns the key can create codes in the project that holds the template.
- Every endpoint is `POST https://open.cli.im/api/v2/rpc/{path}` with a JSON body. Successful results are in `data`. See [openapi.json](https://cli.im/open-api/en/openapi/v2/overview.md#openapi-json) for full field definitions.

## Call sequence

| Step | Endpoint | Purpose |
|---|---|---|
| 1 | `templates/listEditable` | Find the template |
| 2 | `templates/getSchema` | Get the template version and each field's `field_id` |
| 3 | `assets/requestUpload`, `assets/getUpload` | Upload images or attachments first; skip if there are none |
| 4 | `qrcodes/prevalidate` | Validate the whole batch without creating anything |
| 5 | `qrcodes/createBatch` | Submit the creation task |
| 6 | `qrcodeTasks/get` | Poll task progress |
| 7 | `qrcodeTasks/getResults` | Read back each code's ID and link |

### Step 1: Find the template

```bash
curl -sS -X POST 'https://open.cli.im/api/v2/rpc/templates/listEditable' \
  -H "Authorization: Bearer ${CAOLIAO_API_KEY}" \
  -H 'Content-Type: application/json' \
  -d '{"page": 1, "page_size": 20}'
```

The response lists template summaries. Keep paging while `has_more` is true, even if a page comes back empty. Note the `template_id` you want.

### Step 2: Get fields and version

```json
{"template_id": "<template_id>"}
```

Send this to `templates/getSchema`. Take three things from the response:

- `template_version`: pass it unchanged in the next two steps. It changes when the template is edited, so read it again if that happens.
- The field list: fields with `variable` set to true are filled in per sub-code. Use each field's `field_id` as the key for its value.
- `capabilities.create_children`: must be true before you can create sub-codes under this template.

### Step 3: Upload images and attachments (optional) {#upload}

Image and file fields do not accept external URLs. Upload the file first to get a `file_key`.

1. Call `assets/requestUpload`. `size` is the file's exact size in bytes, up to 20 MiB. `mime_type` must match the `Content-Type` you upload with.

   ```json
   {
     "file_name": "boiler-01.jpg",
     "mime_type": "image/jpeg",
     "size": 482133,
     "idempotency_key": "upload-boiler-01-20261118"
   }
   ```

2. The response contains `file_key`, a state and `upload`. Send the raw file bytes to `upload.url` using `upload.method` (PUT) and every header in `upload.headers`, unchanged. This request goes straight to the storage service: do not add `Authorization`, and do not use multipart or base64.
3. Call `assets/getUpload` with `{"file_key": "<file_key>"}`. Only `temporary_available` can be referenced. Check again later while it is `uploading`; request a new upload after `failed` or `expired`.
4. In the creation request, set the field to `[{"file_key": "<file_key>"}]`.

Temporary files expire, so create the codes soon after uploading.

### Step 4: Prevalidate

```json
{
  "template_id": "<template_id>",
  "template_version": "<template_version>",
  "save_plan": true,
  "items": [
    {
      "item_key": "EQ-001",
      "name": "Boiler 1",
      "values": {
        "<field_id_location>": "Power plant, east side",
        "<field_id_photo>": [{"file_key": "<file_key>"}]
      }
    },
    {
      "item_key": "EQ-002",
      "name": "Boiler 2",
      "values": {"<field_id_location>": "Power plant, west side"}
    }
  ]
}
```

Send this to `qrcodes/prevalidate`.

- `item_key` is a stable identifier from your own system, such as an asset number. You use it later to match each result.
- A batch holds at most 100 items and the request body at most 1 MiB. Split larger lists into several batches.
- Without `category_id`, sub-codes go into the folder named after the template.
- Prevalidation creates nothing. It returns `valid`, `requested_count`, `errors`, `warnings` and samples. When `valid` is true and you sent `save_plan: true`, it also returns a `plan_id` that is valid for 30 minutes.
- If there are `errors`, fix them and validate again.

### Step 5: Submit the task

```json
{"plan_id": "<plan_id>", "idempotency_key": "eq-import-20261118-batch-01"}
```

Send this to `qrcodes/createBatch`. With a `plan_id` you do not send `items` again.

The response has `task_id`, `batch_id`, `status`, `total`, `processed_count` and `poll_after_seconds`. A queued task does not mean the codes exist yet.

**Idempotency key**
You generate `idempotency_key`, one per batch. If a request times out or the outcome is unclear, retry with **the same key and the same parameters**. The service returns the original task and creates nothing twice. Retrying with a new key creates a second set of codes.


### Step 6: Poll progress

```json
{"task_id": "<task_id>"}
```

Send this to `qrcodeTasks/get` at the interval given by `poll_after_seconds` until `status` is no longer in progress. An overall `succeeded` only means the task finished. Check each item in the next step.

### Step 7: Read per-item results

```json
{"task_id": "<task_id>", "page": 1, "page_size": 100}
```

Send this to `qrcodeTasks/getResults` and page until `has_more` is false. Each item carries `item_key`, a status, `qrcode_id`, `coding` and `web_url`. Match them against your list by `item_key`:

- `succeeded`: the code exists and its fields and images are saved.
- `content_pending`: the code exists and its content is still being processed. Check again later.
- Failed items include the reason. Fix them and resubmit only the failed items with a new idempotency key.

## Related endpoints

- One code at a time: `qrcodes/create` (standard code), `qrcodes/createUrlJump` (redirect code), `qrcodes/createMultiUrl` (multi-link code), `staticQrcodes/create` (static code).
- No template yet: create one with `templates/create`, or start from an official template. See [management endpoints](https://cli.im/open-api/en/openapi/v2/management.md).
- Printing afterwards: see [Export printable labels](https://cli.im/open-api/en/openapi/v2/scenarios/export-labels.md).
- HTTP 429: see [rate limits](https://cli.im/open-api/en/openapi/v2/error-codes.md#rate-limit).
