API guide · Quickstart · Python

Generate PDFs from JSON in Python

This quickstart turns a JSON array into PDFs with the RowScribe API: one PDF for each object in the array, made from a template you design in RowScribe. The whole program is about 75 lines of Python using the requests package. It sends the rows, waits for the job and saves the result.

Last updated November 27, 2026

What you need

  • Python 3.9 or later, with the requests package.
  • A template. In RowScribe, create a PDF template from the Award Certificate starter. The example rows below have its columns. To use your own template, give each row that template's columns instead.
  • An API key with the templates:read and jobs:write scopes, from Developers → API. API access is on Starter and above. The key is shown once, so copy it then.

Steps

  1. Set your key and template

    The program reads both from environment variables. The template's id is in its address in the editor (/templates/{id}/edit/pdf), or in GET /templates.

    macOS / Linux
    export ROWSCRIBE_API_KEY="rsc_…"
    export ROWSCRIBE_TEMPLATE_ID="your template's id"
    Windows (PowerShell)
    $env:ROWSCRIBE_API_KEY = "rsc_…"
    $env:ROWSCRIBE_TEMPLATE_ID = "your template's id"
  2. Save the rows

    Each object becomes one PDF, and each key is a column the template prints. Save this as rows.json.

    rows.json
    [
      {
        "OrganizationName": "Acme Inc.",
        "RecipientName": "John Smith",
        "AwardTitle": "Outstanding Customer Service",
        "AwardDescription": "For outstanding dedication to our customers in 2026.",
        "Date": "December 12, 2026",
        "SignerName": "Sarah Johnson",
        "SignerTitle": "Chief Executive Officer",
        "SecondSignerName": "Michael Brown",
        "SecondSignerTitle": "Head of People"
      },
      {
        "OrganizationName": "Acme Inc.",
        "RecipientName": "Jane Doe",
        "AwardTitle": "Excellence in Teamwork",
        "AwardDescription": "For bringing the whole team together on every project in 2026.",
        "Date": "December 12, 2026",
        "SignerName": "Sarah Johnson",
        "SignerTitle": "Chief Executive Officer",
        "SecondSignerName": "Michael Brown",
        "SecondSignerTitle": "Head of People"
      },
      {
        "OrganizationName": "Acme Inc.",
        "RecipientName": "Emily Davis",
        "AwardTitle": "Five Years of Service",
        "AwardDescription": "For five years of hard work and loyalty to Acme Inc.",
        "Date": "December 12, 2026",
        "SignerName": "Sarah Johnson",
        "SignerTitle": "Chief Executive Officer",
        "SecondSignerName": "Michael Brown",
        "SecondSignerTitle": "Head of People"
      }
    ]
  3. Save the program

    Run this first:

    Terminal
    pip install requests

    Then save the program as generate.py, next to rows.json.

    generate.py
    """Generate one PDF per row of rows.json with the RowScribe API.
    
    Needs Python 3.9 or later and requests (pip install requests). Run: python generate.py
    """
    import json
    import os
    import sys
    import time
    import uuid
    
    import requests
    
    API = "https://rowscribe.com/api/v1"
    session = requests.Session()
    session.headers["X-API-Key"] = os.environ["ROWSCRIBE_API_KEY"]
    template_id = os.environ["ROWSCRIBE_TEMPLATE_ID"]
    
    
    def call(method, path, **kwargs):
        """Every error has a code and a message; stop on the first one."""
        response = session.request(method, f"{API}{path}", timeout=60, **kwargs)
        if not response.ok:
            try:
                error = response.json()
            except ValueError:
                error = {}
            sys.exit(f"{response.status_code} {error.get('code', '')}: {error.get('message', response.reason)}")
        return response
    
    
    def keys(row):
        """A row's columns are its keys, and the keys of the items in any list (an invoice's line items)."""
        for key, value in row.items():
            yield key
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, dict):
                        yield from keys(item)
    
    
    # 1. The template, and the columns each row needs.
    template = call("GET", f"/templates/{template_id}").json()
    with open("rows.json", encoding="utf-8") as f:
        rows = json.load(f)
    columns = {column for row in rows for column in keys(row)}
    missing = [column for column in template["dataColumns"] if column not in columns]
    if missing:
        sys.exit(f"rows.json has no {', '.join(missing)}, which {template['name']} uses.")
    
    # 2. One job: each row becomes one PDF. The Idempotency-Key makes a retried request safe.
    response = call(
        "POST",
        "/jobs",
        headers={"Idempotency-Key": str(uuid.uuid4())},
        json={"templateId": template_id, "rows": rows},
    )
    job = response.json()
    print(f"Job {job['id']}: {job['totalRows']} rows")
    
    # 3. Wait for it, checking as often as Retry-After says.
    deadline = time.time() + 10 * 60
    while job["status"] in ("pending", "scheduled", "processing"):
        if time.time() > deadline:
            sys.exit(f"Still {job['status']} after 10 minutes; job {job['id']} carries on in RowScribe.")
        time.sleep(int(response.headers.get("Retry-After", 5)))
        response = call("GET", f"/jobs/{job['id']}")
        job = response.json()
    
    if job["status"] != "completed":
        sys.exit(f"Job {job['status']}: {job.get('error') or 'see the job in RowScribe'}")
    
    # 4. Download: one PDF, or a ZIP with a PDF per row.
    file = call("GET", f"/jobs/{job['id']}/download")
    name = "output.pdf" if "pdf" in file.headers.get("Content-Type", "") else "output.zip"
    with open(name, "wb") as f:
        f.write(file.content)
    print(f"Saved {name}")
  4. Run it

    Terminal
    python generate.py

    It prints the job and the file it saved: output.zip, with a PDF for each row, or output.pdf when the job's documents are merged into one. Each row counts as one document toward your plan's monthly allowance.

    Output
    Job 8d0f6c2a-4b1e-4c57-9a3e-2f6d1b7c9e40: 3 rows
    Saved output.zip

How it works

  1. GET /templates/{id} reads the columns the template needs. The program stops if none of the rows has one of them: the API refuses a job with a missing column, and this says which one before anything is sent. A column can also be a key of the items in a row's list, such as an invoice's line items in "Items": [{ "Description": …, "Qty": … }].
  2. POST /jobs creates one job for all the rows, with an Idempotency-Key so a retried request can't create it twice.
  3. GET /jobs/{id} checks on the job as often as its Retry-After header says, until it has finished. It gives up after ten minutes; the job carries on either way.
  4. GET /jobs/{id}/download saves the output.

Every error the API returns has a code and a message, and the program stops with both. The errors table lists every code.

Next steps

  • Be told when it's done. In production a webhook beats checking: RowScribe posts a signed job.completed event to your server when the documents are ready. See Webhooks.
  • Email each person their PDF. Add a delivery to the job to send each row's PDF from your connected Gmail or Outlook, or to upload the output to your own storage. See Delivering documents.
  • Every endpoint is in the API reference, with a Postman collection.
  • The same program in Node.js and C#, and all three on GitHub.