Skip to content

Guide · Developer

PDF API authentication: create, store and rotate API keys

Authenticate SublimePDF API calls with a bearer key: create keys, store them server-side, use one per environment and agent, rotate, revoke and handle 401.

Updated 13 min readSublimePDF Team

Every SublimePDF API request is authenticated with one header: Authorization: Bearer followed by an API key you create in the app. The header is the easy part. The work is in keeping the key on servers you control, giving each environment and each agent its own key, and being able to replace a key in minutes when it leaks or a teammate leaves.

This guide covers that routine end to end: creating a key, making a first authenticated call in curl, Node.js and Python, storing keys, keeping them out of browsers and model prompts, limiting what an AI agent can do with your account, rotating and revoking keys, and handling 401 responses. For the full endpoint list see the API reference.

How authentication works

The API uses bearer authentication over HTTPS. You send the key in the Authorization header of every request:

POST /v1/html-to-pdf HTTP/1.1
Host: api.sublimepdf.com
Authorization: Bearer spdf_live_YOUR_API_KEY
Content-Type: application/json

There is no login call, no session and no token exchange. A key is a long-lived credential that identifies your account, and whoever holds it can make requests that count against your plan's usage. RFC 6750, the specification that defines the bearer scheme, puts the consequence plainly: any party in possession of a bearer token can use it, so the token has to be protected in storage and in transport. Treat a SublimePDF key like a database password.

If the header is missing or the key is not valid or has been revoked, the API answers 401. Nothing else about the request is processed.

Every key starts with spdf_live_, followed by 40 random letters and digits. The fixed prefix makes keys easy to recognise: add a custom pattern such as spdf_live_[A-Za-z0-9]{40} to your secret scanner (GitHub secret scanning, gitleaks, trufflehog) so a key committed by mistake is caught before or right after it is pushed. SublimePDF stores only a SHA-256 hash of each key and its first characters for display, so it cannot show you a key again after creation.

Step 1: Create an API key

Create an account, verify your email address, open the app and go to Settings → API keys. Creating keys needs a verified email and the owner or admin role in the workspace, and a workspace can have up to 50 active keys. Create a key and copy it straight into the place it will live: your secret manager, your hosting provider's environment settings, or a local .env file for development. The full key is shown once, when you create it; if you lose it, create a new one and revoke the old one. Do not paste it into chat, tickets or source files on the way.

Each key has a set of scopes. A new key gets all of them unless you narrow the list when you create it:

ScopeAllows
renderPOST /html-to-pdf, POST /url-to-pdf, POST /templates/{id}/generate
templates:readGET /templates, GET /templates/{id}
templates:writeCreate, update, duplicate and delete templates
jobs:readGET /jobs, GET /jobs/{id}, GET /jobs/{id}/download
jobs:writeDELETE /jobs/{id}
pdf:operationsPOST /merge, POST /split, POST /compress
usage:readGET /usage

A request with a valid key that lacks the endpoint's scope gets 403 with "type": "permission_error". Scopes are fixed when a key is created; to change them, create a new key and revoke the old one.

Name keys after where they are used, for example production-billing-service, staging or support-agent. When you later need to revoke one, the name is what tells you which.

Step 2: Make an authenticated call

GET /templates lists the templates saved in your workspace. It renders nothing and does not count toward your monthly documents, so it is a cheap way to check that a key works. It needs the templates:read scope; for a key without it, GET /usage (scope usage:read) works the same way.

export SUBLIMEPDF_API_KEY="YOUR_API_KEY"
 
curl -s -w "\nHTTP %{http_code}\n" \
  -H "Authorization: Bearer $SUBLIMEPDF_API_KEY" \
  https://api.sublimepdf.com/v1/templates

Node.js 18 or later, no dependencies (save it as check-key.mjs, since it uses top-level await):

const API_BASE = process.env.SUBLIMEPDF_API_BASE_URL ?? "https://api.sublimepdf.com/v1";
const apiKey = process.env.SUBLIMEPDF_API_KEY;
if (!apiKey) throw new Error("SUBLIMEPDF_API_KEY is not set"); // fail at startup, not on the first request
 
const res = await fetch(`${API_BASE}/templates`, {
    headers: { Authorization: `Bearer ${apiKey}` },
});
 
if (res.status === 401) {
    // Do not retry: the same key will be rejected again.
    throw new Error("SublimePDF rejected the API key (401). Check that it is set and not revoked.");
}
if (!res.ok) throw new Error(`SublimePDF returned ${res.status}`);
console.log(await res.json());

Python 3.8 or later, standard library only (save it as check_key.py):

import json
import os
import urllib.error
import urllib.request
 
API_BASE = os.environ.get("SUBLIMEPDF_API_BASE_URL", "https://api.sublimepdf.com/v1")
API_KEY = os.environ["SUBLIMEPDF_API_KEY"]  # KeyError at startup if missing
 
req = urllib.request.Request(
    f"{API_BASE}/templates",
    headers={"Authorization": f"Bearer {API_KEY}"},
)
try:
    with urllib.request.urlopen(req, timeout=30) as res:
        print(json.load(res))
except urllib.error.HTTPError as err:
    if err.code == 401:
        raise SystemExit("SublimePDF rejected the API key (401). Check that it is set and not revoked.")
    raise

Both scripts read the key from the environment and refuse to start without it. A missing key then shows up as a deploy failure you see immediately, not as a stream of 401 responses in production.

What we tested

We ran these three snippets against the local mock of the documented API that ships with the agent quickstart (examples/agent-tool-calling/mock-server.mjs), on Node.js 24.5 and Python 3.9.6:

RequestMock result
Authorization: Bearer <key>200 with the template list
No Authorization header401
Authorization: Bearer with an empty token401
Authorization: Basic ... (wrong scheme)401
Node.js or Python with SUBLIMEPDF_API_KEY unsetExits before sending a request

The mock accepts any non-empty bearer token, so it shows that the client sends the header correctly. It cannot tell a revoked key from a valid one. The API implementation does: its test suite creates a key, authenticates with it, revokes it and checks that the next request gets 401, against a local test database. Those tests ran locally, not against the deployed service, so run the same GET /templates call with your real key, and once with a deliberately wrong key, before you go live.

Step 3: Store the key where only your server can read it

Where the code runsWhere the key lives
Your laptopA .env file listed in .gitignore, or your OS keychain
CI testsThe CI system's encrypted secrets, scoped to the jobs that need them
Production servers and functionsA secret manager or your platform's encrypted environment variables
An agent's tool executorThe executor's environment only (see below)

A few rules cover most leaks:

  • Never commit a key. Not in source, not in a sample config, not in a test fixture. Use placeholders like YOUR_API_KEY in documentation, as this page does.
  • Read the key once at startup from the environment or secret manager. Pass it to the one module that calls SublimePDF instead of reading it all over the codebase.
  • Keep it out of logs. Log that a request was authenticated, or at most the key's display prefix, never the header. The quickstart's mock logs bearer-present or missing for exactly this reason. Check that your HTTP client's debug logging and error reporting tool do not record request headers.
  • Keep it out of URLs. The key goes in a header, never in a query string, where proxies and browser history record it.

The OWASP Secrets Management Cheat Sheet goes further on centralised storage, access auditing and automated rotation if you are building this for a larger team.

Keep keys out of browsers, apps and prompts

An API key is a server-side credential. Anything shipped to a user's device can be read by that user, whatever the minifier does to it.

  • Browser code. Front-end build tools copy some environment variables into the JavaScript bundle on purpose. In Next.js that is any variable prefixed NEXT_PUBLIC_; in Vite it is VITE_ by default (the prefix is configurable with envPrefix). Never give the SublimePDF key a prefix that your build tool exposes to the client. If a page needs a PDF, the browser calls your backend, your backend checks the user's session and calls SublimePDF, and the PDF comes back through your backend.
  • Mobile and desktop apps. Same rule: the app calls your API, your API calls SublimePDF.
  • Model prompts and tool schemas. Anything in a system prompt, a tool description, a tool argument or a tool result is text the model can repeat back to a user. A key in a prompt is a published key.

Limit what an AI agent can reach

When an agent generates PDFs, the model never needs the key. It calls a tool such as generate_pdf. Your tool executor, running on your server, validates the arguments and makes the HTTP request with the key from its own environment. This is the pattern in the agent quickstart, and it gives you a control point the API itself does not have to provide.

Start with the key itself. Give the agent's key only the scopes its tools use, usually just render, plus templates:read if it looks up template IDs. A key without templates:write cannot create or change templates even if the executor has a bug. Scopes are coarse, though: a render key can render any HTML and any of your templates. Restrict the agent in the executor as well:

  • Expose only the operations the agent needs. An invoicing agent needs one render endpoint: POST /html-to-pdf if your executor supplies the HTML, or POST /templates/{id}/generate if it fills templates saved in the app. It does not need POST /templates, so do not give it a tool that creates templates.
  • Allow-list what it can render. If the agent fills saved templates and may only use invoice and credit-note, reject any other ID before the request is sent. If your executor sends HTML, load it from your own template files and let the model supply only the data, so a prompt cannot change the layout or inject markup.
  • Cap input size and call count per conversation, so a looping model cannot spend your monthly renders.
  • Give each agent its own key. If one agent misbehaves, you revoke that key and every other integration keeps working.

If you connect an agent through MCP, the same separation applies. A local stdio MCP server receives the SublimePDF key as an environment variable from its host, and the key never appears in tool schemas or results. Authentication between the MCP host and the MCP server is a separate concern from the REST API key; the MCP integration page covers that transport setup.

One key per environment and per integration

Separate keys cost nothing and make every later incident smaller.

Key nameUsed byIf it leaks
local-dev-<name>One developer's machineRevoke it; nobody else is affected
ciAutomated testsRevoke and update one CI secret
stagingStaging deploysRevoke; production unaffected
production-billingThe invoicing serviceRotate (see below) with no downtime
support-agentOne AI agent's executorRevoke; the agent stops generating PDFs, nothing else does

Development and CI keys draw on the same account usage as production. Point tests at a local mock where you can, as the quickstart does, and keep live calls for a small smoke test.

Rotate and revoke keys

Rotate a key on a schedule, when someone with access leaves, and immediately if you suspect it was exposed. Because the API accepts any valid key for your account, you can rotate without downtime by running old and new keys side by side for a short time:

  1. In Settings → API keys, create a new key with the same purpose and scopes and a new name.
  2. Store it in your secret manager under the same variable name your service already reads.
  3. Redeploy or restart the service so every instance picks up the new value.
  4. Confirm the new key works: a GET /templates call from the service, or your normal traffic succeeding.
  5. Revoke the old key in Settings → API keys. The key list shows when each key was last used, so you can check that the old one has gone quiet first.
  6. Watch for 401 responses for a while. Revocation applies to the next request that uses the key, so any you see come from a process still holding the old key.

If a key has leaked, reverse the order: revoke first, then create and deploy the replacement. A few minutes of failed PDF generation is better than someone else rendering on your account. Removing a leaked key from Git history does not make it safe again, because clones and caches keep it; revoke it either way.

Handle 401 responses

A 401 means the request carried no usable key. Unlike a 503 or 429, retrying the same request will not help:

  • Do not retry. Fail the operation and report it.
  • Alert a person. A sudden run of 401 responses in production usually means a revoked or rotated key, or a deploy that lost its secret.
  • Do not show the raw error to end users. "Document generation is unavailable" is enough.
  • For agents, return a non-retryable tool result. The quickstart's executor tells the model that PDF generation is not configured and that it should not call the tool again, rather than letting the model loop.

A 403 permission_error is the same kind of problem: the key is valid but lacks the scope for that endpoint. Fix the key's scopes rather than retrying. The error body's request_id identifies the request if you need to contact support.

The error handling guide covers the other status codes, which of them are retryable, and how to back off.

Checklist

  • Keys are created in Settings → API keys, one per environment and per agent, with descriptive names and only the scopes they need.
  • A secret scanner matches the spdf_live_ prefix.
  • Keys live in a secret manager or encrypted environment variables, never in source, URLs, logs, browser bundles or prompts.
  • Services read the key once at startup and fail fast if it is missing.
  • Agents reach SublimePDF only through an executor that holds the key and allow-lists operations and template IDs.
  • Rotation follows create, deploy, verify, revoke; a leaked key is revoked first.
  • 401 and 403 are treated as configuration errors: no retries, an alert, a non-retryable result for agents.

For how SublimePDF handles keys, templates and request data on its side, see the security page.

Sources

  1. RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage · accessed 23 November 2026
  2. RFC 9110: HTTP Semantics (401 Unauthorized) · accessed 23 November 2026
  3. OWASP Secrets Management Cheat Sheet · accessed 23 November 2026
  4. Next.js docs: Environment variables · accessed 23 November 2026
  5. Vite docs: Env variables and modes · accessed 23 November 2026

Generate your first PDF with one API call.

Create an account, copy an API key and send HTML, or a template ID with JSON data, from your code or your agent.