Skip to main content
Skip table of contents

9. Document Templates

Document Templates

This scenario demonstrates how to create and use document templates in Circularo. Templates allow you to save document configurations for repeated use, streamlining the creation of similar documents and ensuring consistency across your organization.

Key features:

  • Create reusable document templates with predefined metadata and files

  • Retrieve template information when needed

  • Create new documents based on existing templates

  • Customize template-based documents with additional metadata

Prerequisites

Before working with document templates, you need:

  • A valid authentication token (see the "Authentication & Security" section for details)

  • A PDF file to upload as the template's content

  • Knowledge of the metadata definition and workflow you want to use

Templates are particularly useful for documents that follow a standard format but require different content or metadata for each instance. They help maintain consistency while reducing the effort needed to create new documents.

Step 1 - Upload a PDF file

The first step in creating a document template is to upload the PDF file that will serve as the template's content. This file will be the base document for all documents created from this template.

  • The file is uploaded as a multipart/form-data request

  • The response includes the file ID that will be used in the template creation step

  • The file should represent the standard document structure you want to reuse

Choose a file that represents your standard document format. This could be a contract with placeholders, a report template, or any document structure you frequently use.

Endpoint

CODE
POST /files/saveFile

Request

JSON
POST /files/saveFile?token=DzzVDEBFdIkyMdf2LtMi2xlur2CFmKnbPDXPzsDMaUhQwuEdITg709KOlxSARf35

Content-Type: multipart/form-data

{
  "file": "blob",
  "fileName": "Contract Template"
}

Response

The response contains the following important properties:

  • fileHash - Located at file.id in the response.

    • Example value: IGlmoNcCL79kbhhHw7QIY1zecVVa9Kc4FCtrtixEl2naX9SnloKRcHT1mpE4lNgf

The PDF file has been successfully uploaded and stored in the system. The response includes the file ID that will be used to create the document template.

  • The file.id is the unique identifier for the uploaded file

  • This ID will be referenced when creating the template in the next step

  • The storage information shows your current usage and available quota

Store the file ID for use in the next step. This ID is required to create a template based on this file.

Step 2 - Create a document template

This endpoint creates a new document template using the previously uploaded PDF file. The template will store the file reference, metadata definition, and other settings that can be reused when creating new documents.

  • The name parameter defines a descriptive name for the template

  • The documentType parameter specifies which metadata definition to use

  • The definitionType parameter is set to "ext" for external file-based documents

  • The file parameter references the file ID from the previous step

  • The type parameter is set to "doc" to indicate a document template

Endpoint

CODE
POST /templates

Request

JSON
POST /templates?token=DzzVDEBFdIkyMdf2LtMi2xlur2CFmKnbPDXPzsDMaUhQwuEdITg709KOlxSARf35

Content-Type: application/json

{
  "data": {
    "name": "Standard Contract Template",
    "documentType": "d_default",
    "definitionType": "ext",
    "file": "IGlmoNcCL79kbhhHw7QIY1zecVVa9Kc4FCtrtixEl2naX9SnloKRcHT1mpE4lNgf",
    "type": "doc"
  }
}

Response

The response contains the following important properties:

  • templateId - Located at id in the response.

    • Example value: 87bf5ae3-63d4-41f6-8ede-945815389e66

The document template has been successfully created and is now available for use.

  • The response includes the template ID which will be used to reference this template

  • The template stores the file reference, metadata definition, and other settings

  • This template can now be used to create multiple documents with consistent structure

Store the template ID for future use. You'll need it when creating documents based on this template.

Step 3 - Retrieve template information

When you need to use a template, you can retrieve its details using this endpoint. If you know the template ID, you can fetch it directly. Alternatively, you can search for templates using the template search endpoint (not shown in this scenario).

  • The templateId parameter specifies which template to retrieve

  • The response includes all template details including the file reference

Endpoint

CODE
GET /templates/:templateId

Request

JSON
GET /templates/87bf5ae3-63d4-41f6-8ede-945815389e66?token=DzzVDEBFdIkyMdf2LtMi2xlur2CFmKnbPDXPzsDMaUhQwuEdITg709KOlxSARf35

Response

JSON
{
  "definitionType": "ext",
  "documentType": "d_default",
  "file": "IGlmoNcCL79kbhhHw7QIY1zecVVa9Kc4FCtrtixEl2naX9SnloKRcHT1mpE4lNgf",
  "name": "Standard Contract Template",
  "__id": "87bf5ae3-63d4-41f6-8ede-945815389e66",
  "__addedBy": "mary.griffin@circularo.com",
  "__addedOn": "2023-07-11T13:38:36.909Z",
  "__owner": "mary.griffin@circularo.com",
  "__users": [],
  "__groups": [],
  ...
}

The response includes detailed information about the requested template.

  • The name field contains the template's descriptive name

  • The file field contains the file ID of the template's content

  • The documentType field indicates which metadata definition is used

  • The __owner field shows who created the template

  • The __users and __groups fields show sharing settings

Step 4 - Create a document from template

This endpoint creates a new document based on the previously created template. The template provides a reference point, but all document data must still be explicitly provided in the request.

  • The customTemplate parameter references the template ID to use

  • The documentTitle and other metadata fields must be explicitly provided for this document

  • All required document data must be included in the request - data is NOT automatically fetched from the template

  • The cloneMainFile option is crucial as it creates a copy of the template's file for this document

  • The workflow parameter defines which workflow to apply to the new document

Important: The template ID (customTemplate) only serves as a reference - it does NOT automatically populate the document with template data. You must explicitly provide all required document data in the request.

The cloneMainFile: true option is essential when creating documents from templates. It prevents multiple documents to reference the same file.

Endpoint

CODE
POST /documents

Request

JSON
POST /documents?token=DzzVDEBFdIkyMdf2LtMi2xlur2CFmKnbPDXPzsDMaUhQwuEdITg709KOlxSARf35

Content-Type: application/json

{
  "body": {
    "documentType": "d_default",
    "documentTitle": "Company memo from template",
    "customTemplate": "87bf5ae3-63d4-41f6-8ede-945815389e66",  //ID of the template to use as the base for this document
    "pdfFile": {
      "content": "IGlmoNcCL79kbhhHw7QIY1zecVVa9Kc4FCtrtixEl2naX9SnloKRcHT1mpE4lNgf"  //Reference to the template's file that will be cloned
    }
  },
  "optionalData": {
    "cloneMainFile": true  //Creates a copy of the template's file for this document
  },
  "definitionType": "ext",
  "workflow": "wf_archive"
}

Response

The response contains the following important properties:

  • documentId - Located at results[0].documentId in the response.

    • Example value: 9e900d4b-0f1d-4f84-b9eb-b4a7fbaa3d61

The document has been successfully created based on the template reference.

  • The response includes the document ID of the newly created document

  • The document uses a copy of the template's file, not the original file

  • All document data was provided explicitly in the request - no data was automatically fetched from the template

  • The document starts in the initial state of the specified workflow

Remember that templates serve as a reference point only. You must explicitly provide all required document data in each document creation request.


Document Templates Summary

You have successfully learned how to create and use document templates in the Circularo system.

Key Concepts

  • Document Templates: Reference configurations that store file references and metadata definitions

  • Manual Data Entry: All document data must be explicitly provided in the creation request - no data is automatically fetched from templates

  • Template Retrieval: Templates can be fetched by ID or searched using various criteria to view their structure

  • File Cloning: When creating documents from templates, the template's file is cloned to ensure independence

  • Customization: Template-based documents require explicit specification of all metadata values

Benefits of Using Templates

  • Consistency: Ensure all documents of a certain type follow the same structure

  • Efficiency: Reduce the time needed to create similar documents

  • Standardization: Enforce organizational standards for document creation

  • Collaboration: Share templates with team members to streamline workflows

Example Implementation

See our OpenAPI documentation to learn about the full set of API endpoints and parameters.

Please use proper exception handling and function decomposition in your own code. The code is provided for illustrative purposes only and is not intended for production use.

JAVASCRIPT
// Document template usage example
const URL = "https://sandbox.circularo.com";
const API_PATH = "/api/v1";
const TOKEN = "YOUR_AUTH_TOKEN"; // Obtained from login or API key

try {
    // Step 1: Upload a PDF file for the template
    const formData = new FormData();
    formData.append('fileName', 'Contract Template');
    formData.append('file', fs.createReadStream('path/to/template.pdf'));   // Using Node.js fs module

    const uploadResponse = await fetch(`${URL}${API_PATH}/files/saveFile?token=${TOKEN}`, {
        method: 'POST',
        body: formData
    });
    if (!uploadResponse.ok) {
        throw new Error(`File upload failed: ${uploadResponse.status} ${uploadResponse.statusText}`);
    }

    const uploadData = await uploadResponse.json();
    const fileId = uploadData.file.id;

    // Step 2: Create a document template
    const createTemplateResponse = await fetch(`${URL}${API_PATH}/templates?token=${TOKEN}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            data: {
                name: "Standard Contract Template",
                documentType: "d_default",
                definitionType: "ext",
                file: fileId,
                type: "doc"
            }
        })
    });
    if (!createTemplateResponse.ok) {
        throw new Error(`Template creation failed: ${createTemplateResponse.status} ${createTemplateResponse.statusText}`);
    }

    const templateData = await createTemplateResponse.json();
    const templateId = templateData.id;
    console.log(`Template created with ID: ${templateId}`);

    // Later, when you need to use the template...

    // Step 3: Retrieve template information (optional)
    const templateResponse = await fetch(`${URL}${API_PATH}/templates/${templateId}?token=${TOKEN}`);
    if (!templateResponse.ok) {
        throw new Error(`Failed to retrieve template: ${templateResponse.status} ${templateResponse.statusText}`);
    }

    const template = await templateResponse.json();
    console.log(`Using template: ${template.name}`);

    // Step 4: Create a document from the template
    const createDocumentResponse = await fetch(`${URL}${API_PATH}/documents?token=${TOKEN}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            body: {
                // All document data must be explicitly provided here - nothing is auto-fetched from the template
                documentType: template.documentType,
                documentTitle: "Client Contract - ABC Corporation",
                customTemplate: templateId,  // Template reference only
                pdfFile: {
                    content: template.file
                }
            },
            optionalData: {
                cloneMainFile: true  // Important: creates a copy of the template's file
            },
            definitionType: template.definitionType,
            workflow: "wf_archive"
        })
    });
    if (!createDocumentResponse.ok) {
        throw new Error(`Document creation failed: ${createDocumentResponse.status} ${createDocumentResponse.statusText}`);
    }

    const documentData = await createDocumentResponse.json();
    const documentId = documentData.results[0].documentId;

    console.log(`Document created from template with ID: ${documentId}`);

} catch (error) {
    console.error('Error working with templates:', error.message);
}

Remember that the template ID (customTemplate) only serves as a reference. All document data must be explicitly provided in the document creation request - no data is automatically fetched from the template.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.