{
	"openapi": "3.1.0",
	"info": {
		"title": "Document generation API",
		"version": "1.0.0",
		"description": "Generate PDF and DOCX documents from templates made in the app. Every address is on your organization's regional node. Refusals are JSON: `{ \"success\": false, \"failure\": { \"code\", \"message\", \"details\"? } }`; branch on the status and `failure.code`, not on the message."
	},
	"servers": [
		{
			"url": "https://{node}/api/v1",
			"variables": {
				"node": {
					"default": "node.example.com",
					"description": "Your organization's regional node, as the app shows it in Templates → ⋯ → API request."
				}
			}
		}
	],
	"security": [{ "ApiKey": [] }, { "Bearer": [] }],
	"tags": [
		{
			"name": "Documents",
			"description": "Generation and what it needs: templates and their data schema."
		},
		{ "name": "Service", "description": "The node's limits, without a key." }
	],
	"paths": {
		"/documents/generate": {
			"post": {
				"tags": ["Documents"],
				"operationId": "generateDocument",
				"summary": "Generate a PDF or DOCX from a template, or check the request (dryRun)",
				"description": "Needs a key with the `write` scope. A successful generation spends credits; `dryRun`, a replay by `Idempotency-Key` and refusals do not.",
				"parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
				"requestBody": {
					"required": true,
					"content": {
						"application/json": {
							"schema": { "$ref": "#/components/schemas/GenerateRequest" },
							"example": {
								"templateId": "<template-id>",
								"data": { "client": { "name": "Aliya" } },
								"dryRun": true
							}
						}
					}
				},
				"responses": {
					"200": {
						"description": "`dryRun: true`: the request checked, nothing rendered or charged.",
						"headers": {
							"X-TezDoc-Template-Version": {
								"$ref": "#/components/headers/TemplateVersion"
							},
							"X-TezDoc-Template-Version-Id": {
								"$ref": "#/components/headers/TemplateVersionId"
							},
							"X-TezDoc-Resolved-By": {
								"$ref": "#/components/headers/ResolvedBy"
							},
							"X-TezDoc-Mode": { "$ref": "#/components/headers/Mode" }
						},
						"content": {
							"application/json": {
								"schema": { "$ref": "#/components/schemas/DryRunReceipt" }
							}
						}
					},
					"201": {
						"description": "The document. Not stored for download later: keep it.",
						"headers": {
							"X-TezDoc-Template-Version": {
								"$ref": "#/components/headers/TemplateVersion"
							},
							"X-TezDoc-Template-Version-Id": {
								"$ref": "#/components/headers/TemplateVersionId"
							},
							"X-TezDoc-Resolved-By": {
								"$ref": "#/components/headers/ResolvedBy"
							},
							"X-TezDoc-Mode": { "$ref": "#/components/headers/Mode" },
							"X-TezDoc-Document-Id": {
								"description": "The document's id, for `GET /documents/{id}`.",
								"schema": { "type": "string" }
							},
							"Idempotent-Replayed": {
								"description": "`true` when this is the stored answer to an earlier request with the same `Idempotency-Key`.",
								"schema": { "type": "string", "enum": ["true"] }
							},
							"Content-Disposition": {
								"schema": {
									"type": "string",
									"example": "attachment; filename=document.pdf"
								}
							}
						},
						"content": {
							"application/pdf": {
								"schema": { "type": "string", "format": "binary" }
							},
							"application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
								"schema": { "type": "string", "format": "binary" }
							}
						}
					},
					"400": { "$ref": "#/components/responses/BadRequest" },
					"401": { "$ref": "#/components/responses/Unauthenticated" },
					"402": { "$ref": "#/components/responses/PaymentRequired" },
					"403": { "$ref": "#/components/responses/Forbidden" },
					"404": { "$ref": "#/components/responses/TemplateNotFound" },
					"409": { "$ref": "#/components/responses/Conflict" },
					"410": { "$ref": "#/components/responses/TemplateDeleted" },
					"413": { "$ref": "#/components/responses/PayloadTooLarge" },
					"422": { "$ref": "#/components/responses/Unprocessable" },
					"429": { "$ref": "#/components/responses/TooManyRequests" },
					"500": { "$ref": "#/components/responses/ServerError" },
					"503": { "$ref": "#/components/responses/Unavailable" }
				}
			}
		},
		"/documents/templates": {
			"get": {
				"tags": ["Documents"],
				"operationId": "listTemplates",
				"summary": "The organization's templates and their version numbers",
				"description": "Any valid key. A test key (`sk_test`) lists every template out of the trash; a live key (`sk_live`) only those with a published version.",
				"responses": {
					"200": {
						"description": "The templates.",
						"content": {
							"application/json": {
								"schema": {
									"type": "array",
									"items": { "$ref": "#/components/schemas/TemplateSummary" }
								}
							}
						}
					},
					"401": { "$ref": "#/components/responses/Unauthenticated" },
					"429": { "$ref": "#/components/responses/TooManyRequests" },
					"500": { "$ref": "#/components/responses/ServerError" },
					"503": { "$ref": "#/components/responses/Unavailable" }
				}
			}
		},
		"/documents/templates/{templateId}/schema": {
			"get": {
				"tags": ["Documents"],
				"operationId": "getTemplateSchema",
				"summary": "JSON Schema of the data a template reads",
				"description": "Any valid key. The version is the one a generation with this key would take; `version` names another. Ask once and keep it: the schema changes only with a new version.",
				"parameters": [
					{
						"name": "templateId",
						"in": "path",
						"required": true,
						"schema": { "type": "string" }
					},
					{
						"name": "version",
						"in": "query",
						"required": false,
						"description": "`production`, `test`, `latest` or a version number. A live key gets 403 for `test`, `latest` and a never published number.",
						"schema": { "type": "string", "examples": ["production", "3"] }
					}
				],
				"responses": {
					"200": {
						"description": "The schema and the version it is for.",
						"content": {
							"application/json": {
								"schema": { "$ref": "#/components/schemas/TemplateDataSchema" }
							}
						}
					},
					"400": { "$ref": "#/components/responses/BadRequest" },
					"401": { "$ref": "#/components/responses/Unauthenticated" },
					"403": { "$ref": "#/components/responses/VersionNotAllowed" },
					"404": { "$ref": "#/components/responses/TemplateNotFound" },
					"409": { "$ref": "#/components/responses/Conflict" },
					"410": { "$ref": "#/components/responses/TemplateDeleted" },
					"422": { "$ref": "#/components/responses/Unprocessable" },
					"429": { "$ref": "#/components/responses/TooManyRequests" },
					"500": { "$ref": "#/components/responses/ServerError" },
					"503": { "$ref": "#/components/responses/Unavailable" }
				}
			}
		},
		"/documents/{documentId}": {
			"get": {
				"tags": ["Documents"],
				"operationId": "getDocument",
				"summary": "The record of a generated document, without the file",
				"description": "Any valid key of the organization, a `write`-only one included.",
				"parameters": [
					{
						"name": "documentId",
						"in": "path",
						"required": true,
						"schema": { "type": "string" }
					}
				],
				"responses": {
					"200": {
						"description": "The record.",
						"content": {
							"application/json": {
								"schema": { "$ref": "#/components/schemas/DocumentRecord" }
							}
						}
					},
					"401": { "$ref": "#/components/responses/Unauthenticated" },
					"404": { "$ref": "#/components/responses/NotFound" },
					"429": { "$ref": "#/components/responses/TooManyRequests" },
					"500": { "$ref": "#/components/responses/ServerError" },
					"503": { "$ref": "#/components/responses/Unavailable" }
				}
			}
		},
		"/capabilities": {
			"get": {
				"tags": ["Service"],
				"operationId": "getCapabilities",
				"summary": "The node's engines, size limits and fonts",
				"description": "No key needed. Counted against the per-address request limit.",
				"security": [],
				"responses": {
					"200": {
						"description": "The node's capabilities.",
						"content": {
							"application/json": {
								"schema": { "$ref": "#/components/schemas/Capabilities" }
							}
						}
					},
					"429": { "$ref": "#/components/responses/TooManyRequests" }
				}
			}
		}
	},
	"components": {
		"securitySchemes": {
			"ApiKey": {
				"type": "apiKey",
				"in": "header",
				"name": "X-Api-Key",
				"description": "A key made in the app: `sk_test_…` or `sk_live_…`."
			},
			"Bearer": {
				"type": "http",
				"scheme": "bearer",
				"description": "The same key as `Authorization: Bearer <key>`."
			}
		},
		"parameters": {
			"IdempotencyKey": {
				"name": "Idempotency-Key",
				"in": "header",
				"required": false,
				"description": "1 to 255 characters. A repeat of the same request gets the same document (`Idempotent-Replayed: true`) and is not charged again; on the free plan with its credits spent, a document already made is given back at most 3 more times, then refused like a new request. The same value with another request is 422 `IDEMPOTENCY_KEY_REUSED` once the first made its document; any request while the first runs is 409 `IDEMPOTENCY_IN_PROGRESS`; a refused or failed request frees the value for a corrected retry.",
				"schema": { "type": "string", "minLength": 1, "maxLength": 255 }
			}
		},
		"headers": {
			"TemplateVersion": {
				"description": "The number of the template version used.",
				"schema": { "type": "string", "pattern": "^[0-9]+$" }
			},
			"TemplateVersionId": {
				"description": "The id of the template version used.",
				"schema": { "type": "string" }
			},
			"ResolvedBy": {
				"description": "How the version was chosen.",
				"schema": { "$ref": "#/components/schemas/ResolvedBy" }
			},
			"Mode": {
				"description": "The key's mode.",
				"schema": { "$ref": "#/components/schemas/Mode" }
			},
			"RetryAfter": {
				"description": "Seconds to wait: `GENERATION_CONCURRENCY_LIMIT` and `SERVER_BUSY` (5 now), `DAILY_CREDIT_LIMIT` and `KEY_CREDIT_LIMIT` (until midnight UTC; none for a document dearer than the daily limit itself). `RATE_LIMITED` has none: see `Retry-After-short`, `Retry-After-long`, `Retry-After-ip`, `Retry-After-ipBurst`.",
				"schema": { "type": "integer" }
			},
			"RetryAfterNamed": {
				"description": "Seconds until the named request counter frees (`RATE_LIMITED`).",
				"schema": { "type": "integer" }
			}
		},
		"responses": {
			"BadRequest": {
				"description": "`VALIDATION_FAILED`: the body, `Idempotency-Key` or `version` is malformed; `details` lists the fields.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"Unauthenticated": {
				"description": "`UNAUTHENTICATED`: no key, a wrong or revoked one, or the organization is blocked. `KEY_EXPIRED`: the key is past its expiry.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"PaymentRequired": {
				"description": "`PAYMENT_REQUIRED`: a live key, and the plan no longer includes live keys (its grace period after a downgrade is over); the reason is in `message`. `CREDITS_EXHAUSTED`: the free plan's credits of the month are spent, or this document costs more than is left (checked after the layout, nothing charged); `details.limit`, `details.spent`, `details.resetsAt`, and `details.cost` for a document dearer than one credit. A document dearer than the month's limit itself never fits on the free plan.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"VersionNotAllowed": {
				"description": "`VERSION_NOT_ALLOWED`: a live key asked for an unpublished version, `latest` or `test`. Reading a schema needs no scope.",
				"content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorReceipt" } } }
			},
			"Forbidden": {
				"description": "`FORBIDDEN`: the key lacks the `write` scope. `VERSION_NOT_ALLOWED`: a live key asked for an unpublished version, `latest` or `test`.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"TemplateNotFound": {
				"description": "`TEMPLATE_NOT_FOUND`: no such template or version in the organization, or the template has no content.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"NotFound": {
				"description": "`NOT_FOUND`: no such document in the organization.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"Conflict": {
				"description": "`TEMPLATE_NOT_PUBLISHED`: no published version. `REVISION_MISMATCH`: not the version of `expectedVersion`, both in `details`. `IDEMPOTENCY_IN_PROGRESS`: a request with this `Idempotency-Key` still runs.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"TemplateDeleted": {
				"description": "`TEMPLATE_DELETED`: the template is in the trash.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"PayloadTooLarge": {
				"description": "`PAYLOAD_TOO_LARGE`: the body is over 102,400 bytes.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"Unprocessable": {
				"description": "`VALIDATION_FAILED`: `strict` found problems with `data`, `details` lists them. `IDEMPOTENCY_KEY_REUSED`, `HYDRATION_BUDGET_EXCEEDED`, `DOCUMENT_SCHEMA_UNSUPPORTED`.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"TooManyRequests": {
				"description": "`RATE_LIMITED`: per key 10 a second and 300 a minute, per address 20 and 600, each kind of request counted apart. `GENERATION_CONCURRENCY_LIMIT`: the organization already generates two documents. `DAILY_CREDIT_LIMIT`: the free plan's daily credits are spent, or this document costs more than is left today; a document dearer than the daily limit itself never fits and gets no `Retry-After`. `KEY_CREDIT_LIMIT`: this API key's own daily credit limit, set by the organization, is reached; `details` has `limit`, `spent`, `resetsAt`.",
				"headers": {
					"Retry-After": { "$ref": "#/components/headers/RetryAfter" },
					"Retry-After-short": {
						"$ref": "#/components/headers/RetryAfterNamed"
					},
					"Retry-After-long": {
						"$ref": "#/components/headers/RetryAfterNamed"
					},
					"Retry-After-ip": { "$ref": "#/components/headers/RetryAfterNamed" },
					"Retry-After-ipBurst": {
						"$ref": "#/components/headers/RetryAfterNamed"
					}
				},
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"ServerError": {
				"description": "`RENDER_FAILED`: the document could not be built, retry once. `INTERNAL_ERROR`.",
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			},
			"Unavailable": {
				"description": "`CONTROL_PLANE_UNAVAILABLE`: the key could not be checked now, the key itself is fine. `SERVER_BUSY`: retry after `Retry-After`. `REGION_DISABLED`: the region is switched off.",
				"headers": {
					"Retry-After": { "$ref": "#/components/headers/RetryAfter" }
				},
				"content": {
					"application/json": {
						"schema": { "$ref": "#/components/schemas/ErrorReceipt" }
					}
				}
			}
		},
		"schemas": {
			"ResolvedBy": {
				"type": "string",
				"enum": ["production", "latest", "pinned", "test"]
			},
			"Mode": { "type": "string", "enum": ["live", "test", "dashboard"] },
			"GenerateRequest": {
				"type": "object",
				"required": ["templateId"],
				"properties": {
					"templateId": { "type": "string", "minLength": 1 },
					"data": {
						"type": "object",
						"additionalProperties": true,
						"default": {},
						"description": "The values the template reads; nested at most 64 levels."
					},
					"dryRun": {
						"type": "boolean",
						"default": false,
						"description": "Check the request and answer 200 with a receipt; nothing is rendered or charged."
					},
					"outputFormat": {
						"type": "string",
						"enum": ["pdf", "docx"],
						"default": "pdf"
					},
					"version": {
						"description": "Omitted: the key decides (live: the published version; test: the one on review, else the published one, else the latest).",
						"oneOf": [
							{ "type": "string", "enum": ["production", "latest", "test"] },
							{ "type": "integer", "minimum": 1 }
						]
					},
					"expectedVersion": {
						"type": "integer",
						"minimum": 1,
						"description": "`template.version` of a dry run: a different version refuses with 409 `REVISION_MISMATCH`."
					},
					"strict": {
						"type": "boolean",
						"default": false,
						"description": "Refuse with 422 `VALIDATION_FAILED` on any problem with `data`, before rendering."
					}
				}
			},
			"DryRunReceipt": {
				"type": "object",
				"required": ["success", "dryRun", "template", "mode", "warnings"],
				"properties": {
					"success": { "const": true },
					"dryRun": { "const": true },
					"template": {
						"type": "object",
						"required": ["id", "version", "versionId", "resolvedBy"],
						"properties": {
							"id": { "type": "string" },
							"version": { "type": "integer" },
							"versionId": { "type": "string" },
							"resolvedBy": { "$ref": "#/components/schemas/ResolvedBy" }
						}
					},
					"mode": { "$ref": "#/components/schemas/Mode" },
					"warnings": {
						"type": "array",
						"items": { "type": "object" },
						"description": "Always empty for current templates; problems are in `diagnostics` and `templateIssues`."
					},
					"pages": {
						"type": "integer",
						"description": "Pages by the service's layout: the credits a generation would cost follow from it."
					},
					"credits": {
						"type": "integer",
						"description": "Credits the same generation would spend: 1 for up to 10 pages, plus 1 for each further 10 started."
					},
					"diagnostics": {
						"type": "array",
						"items": {
							"type": "object",
							"required": ["severity", "code", "message"],
							"properties": {
								"severity": { "type": "string", "enum": ["error", "warning"] },
								"code": { "type": "string" },
								"message": { "type": "string" }
							}
						}
					},
					"templateIssues": {
						"type": "array",
						"items": { "$ref": "#/components/schemas/FailureIssue" },
						"description": "Problems only the template's author can fix."
					}
				}
			},
			"FailureIssue": {
				"type": "object",
				"required": ["code", "message", "path"],
				"properties": {
					"code": {
						"type": "string",
						"examples": ["field-missing", "field-unknown", "field-type"]
					},
					"message": { "type": "string" },
					"path": {
						"type": "array",
						"items": { "type": ["string", "integer"] },
						"description": "Where in `data`; empty when the problem is a template tag."
					},
					"target": {
						"type": "object",
						"required": ["expression"],
						"properties": {
							"nodeType": { "type": "string" },
							"expression": { "type": "string" }
						}
					},
					"source": { "type": "string", "enum": ["data", "template"] },
					"severity": { "type": "string", "enum": ["error", "warning"] }
				}
			},
			"FailureCode": {
				"type": "string",
				"description": "Codes are only added, never renamed or removed.",
				"enum": [
					"VALIDATION_FAILED",
					"UNAUTHENTICATED",
					"KEY_EXPIRED",
					"PAYMENT_REQUIRED",
					"CREDITS_EXHAUSTED",
					"FORBIDDEN",
					"VERSION_NOT_ALLOWED",
					"TEMPLATE_NOT_FOUND",
					"NOT_FOUND",
					"TEMPLATE_NOT_PUBLISHED",
					"REVISION_MISMATCH",
					"IDEMPOTENCY_IN_PROGRESS",
					"TEMPLATE_DELETED",
					"PAYLOAD_TOO_LARGE",
					"IDEMPOTENCY_KEY_REUSED",
					"HYDRATION_BUDGET_EXCEEDED",
					"DOCUMENT_SCHEMA_UNSUPPORTED",
					"RATE_LIMITED",
					"GENERATION_CONCURRENCY_LIMIT",
					"DAILY_CREDIT_LIMIT",
					"KEY_CREDIT_LIMIT",
					"RENDER_FAILED",
					"INTERNAL_ERROR",
					"CONTROL_PLANE_UNAVAILABLE",
					"SERVER_BUSY",
					"REGION_DISABLED"
				]
			},
			"ErrorReceipt": {
				"type": "object",
				"required": ["success", "failure"],
				"properties": {
					"success": { "const": false },
					"failure": {
						"type": "object",
						"required": ["code", "message"],
						"properties": {
							"code": { "$ref": "#/components/schemas/FailureCode" },
							"message": {
								"type": "string",
								"description": "For the developer, in English; do not branch on it."
							},
							"details": {
								"description": "Its shape follows the code: `FailureIssue[]` for `VALIDATION_FAILED`, `{ limit, spent, resetsAt }` for the credit limits."
							}
						}
					}
				},
				"example": {
					"success": false,
					"failure": {
						"code": "TEMPLATE_NOT_FOUND",
						"message": "Template not found"
					}
				}
			},
			"TemplateSummary": {
				"type": "object",
				"required": [
					"id",
					"name",
					"description",
					"updatedAt",
					"publishedVersion",
					"testVersion",
					"latestVersion"
				],
				"properties": {
					"id": {
						"type": "string",
						"description": "`templateId` of a generation."
					},
					"name": { "type": "string" },
					"description": { "type": ["string", "null"] },
					"updatedAt": { "type": "string", "format": "date-time" },
					"publishedVersion": { "type": ["integer", "null"] },
					"testVersion": { "type": ["integer", "null"] },
					"latestVersion": { "type": ["integer", "null"] }
				}
			},
			"TemplateDataSchema": {
				"type": "object",
				"required": ["version", "versionId", "resolvedBy", "schema"],
				"properties": {
					"version": { "type": "integer" },
					"versionId": { "type": "string" },
					"resolvedBy": { "$ref": "#/components/schemas/ResolvedBy" },
					"schema": {
						"type": "object",
						"description": "JSON Schema (draft 2020-12) of `data`. A field whose type the template does not fix is `{}`; `x-type` hints a type."
					}
				}
			},
			"DocumentRecord": {
				"type": "object",
				"required": ["id", "status", "createdAt"],
				"additionalProperties": true,
				"description": "Only the fields below are part of the contract; others may appear and go away.",
				"properties": {
					"id": { "type": "string" },
					"status": { "type": "string", "examples": ["completed"] },
					"templateId": {
						"type": ["string", "null"],
						"description": "Null once the template is deleted."
					},
					"templateVersionId": { "type": ["string", "null"] },
					"createdAt": { "type": "string", "format": "date-time" }
				}
			},
			"Capabilities": {
				"type": "object",
				"required": [
					"apiVersion",
					"version",
					"region",
					"engines",
					"limits",
					"fonts"
				],
				"properties": {
					"apiVersion": { "const": "v1" },
					"version": { "type": "string" },
					"region": { "type": ["string", "null"] },
					"engines": {
						"type": "object",
						"required": ["template", "pdf"],
						"properties": {
							"template": { "type": "string" },
							"pdf": { "type": "string" }
						}
					},
					"limits": {
						"type": "object",
						"required": [
							"maxLoopNodes",
							"maxHydratedTextChars",
							"maxExpressionLength",
							"maxBodyBytes"
						],
						"properties": {
							"maxLoopNodes": { "type": "integer" },
							"maxHydratedTextChars": { "type": "integer" },
							"maxExpressionLength": { "type": "integer" },
							"maxBodyBytes": { "type": "integer" }
						}
					},
					"fonts": { "type": "array", "items": { "type": "string" } }
				}
			}
		}
	}
}
