> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pdfnoodle.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Template

> Retrieves the complete template details, including its structure, components, and metadata. This endpoint can also be used to check the status of a template that is currently being created.

<Note>
  This endpoint returns different response structures depending on whether the
  template is fully created or still being processed. Use this endpoint to poll
  for completion when creating templates with AI.
</Note>

GET [https://api.pdfnoodle.com/v1/integration/templates/:templateId](https://api.pdfnoodle.com/v1/integration/templates/:templateId)

## Request

<CodeGroup>
  ```bash cURL theme={null}
  curl --location 'https://api.pdfnoodle.com/v1/integration/templates/invoice-template-001' \
  --header 'Authorization: Bearer pdfnoodle_api_123456789'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    "https://api.pdfnoodle.com/v1/integration/templates/invoice-template-001",
    {
      method: "GET",
      headers: {
        Authorization: "Bearer pdfnoodle_api_123456789",
      },
    }
  );

  const result = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://api.pdfnoodle.com/v1/integration/templates/invoice-template-001',
      headers={
          'Authorization': 'Bearer pdfnoodle_api_123456789'
      }
  )

  result = response.json()
  ```
</CodeGroup>

## Response

This endpoint returns different response structures depending on the template's status:

### Completed Template Response

<CodeGroup>
  ```json Success - Completed Template (200 OK) theme={null}
  {
    "template": {
      "id": "invoice-template-001",
      "displayName": "Standard Invoice",
      "createdAt": "2024-01-15T10:30:00.000Z",
      "updatedAt": "2024-01-15T10:30:00.000Z",
      "style": {
        "header": { "showHeader": true, "headerText": "..." },
        "footer": { "showFooter": true, "footerText": "..." }
      },
      "type": "HTML",
      "html": "<html>...</html>"
    }
  }
  ```
</CodeGroup>

### Template Creation Status Response

<CodeGroup>
  ```json ONGOING - Template Being Created (200 OK) theme={null}
  {
    "status": "ONGOING",
    "templateId": "a1b2c3d4e5",
    "templateHtml": "",
    "metadata": {}
  }
  ```

  ```json SUCCESS - Template Creation Completed (200 OK) theme={null}
  {
    "status": "SUCCESS",
    "templateId": "a1b2c3d4e5",
    "templateHtml": "<html>...</html>",
    "pdfPreviewUrl": "https://s3.amazonaws.com/...",
    "metadata": {
      "timeToCreateTemplate": "45.2 seconds"
    }
  }
  ```

  ```json FAILED - Template Creation Failed (200 OK) theme={null}
  {
    "status": "FAILED",
    "templateId": "a1b2c3d4e5",
    "templateHtml": "",
    "metadata": {
      "errorMessage": "Error message describing what went wrong"
    }
  }
  ```
</CodeGroup>

## Path Parameters

<ParamField path="templateId" type="string" required>
  Template identifier. This can be: - The `name` field from an existing template
  (same as `id` from list templates response) - The `templateId` returned from
  the create template endpoint
</ParamField>

## Response Fields

### Completed Template Response

<ParamField response="template" type="object">
  Complete template object with all database fields
</ParamField>

<ParamField response="template.id" type="string">
  Template identifier (used in other endpoints)
</ParamField>

<ParamField response="template.displayName" type="string">
  Human-readable template name
</ParamField>

<ParamField response="template.createdAt" type="string">
  Template creation timestamp (ISO 8601 format)
</ParamField>

<ParamField response="template.updatedAt" type="string">
  Template last update timestamp (ISO 8601 format)
</ParamField>

<ParamField response="template.style" type="object">
  Template styling configuration (header, footer, etc.)
</ParamField>

<ParamField response="template.type" type="string">
  Template type (e.g., "HTML", "NO\_CODE")
</ParamField>

<ParamField response="template.htmlTemplate" type="string">
  The HTML template content, including Handlebars variables for dynamic content
</ParamField>

### Status Response (for templates being created)

<ParamField response="status" type="string">
  Status of template creation. Possible values: - `ONGOING` - Template creation
  is still in progress - `SUCCESS` - Template has been created successfully -
  `FAILED` - Template creation failed
</ParamField>

<ParamField response="templateId" type="string">
  Template identifier
</ParamField>

<ParamField response="templateHtml" type="string">
  HTML template content. Empty if `ONGOING`, populated if `SUCCESS`
</ParamField>

<ParamField response="pdfPreviewUrl" type="string">
  A signed URL to a PDF preview of the generated template, rendered with sample
  data. The URL is valid for 7 days. Empty string if preview generation failed.
  Only present when `status` is `SUCCESS`.
</ParamField>

<ParamField response="metadata" type="object">
  Additional metadata about the template creation
</ParamField>

<ParamField response="metadata.timeToCreateTemplate" type="string">
  Time taken to create template (only present if `status` is `SUCCESS`)
</ParamField>

<ParamField response="metadata.errorMessage" type="string">
  Error message describing what went wrong (only present if `status` is
  `FAILED`)
</ParamField>

## Status Checking

When creating a template with AI, use this endpoint to poll for completion:

* **`ONGOING`**: Template creation is still in progress. Continue polling.
* **`SUCCESS`**: Template has been created successfully. The `templateHtml` field contains the generated template.
* **`FAILED`**: Template creation failed. Check `metadata.errorMessage` for details.

<Note>
  Status information for templates being created is cached in Redis for 24
  hours. Once a template is fully created, the response format changes to the
  full template object.
</Note>

## Polling Strategy

When polling for template creation status:

* Poll every 10-30 seconds after initial creation
* Stop polling once `status` is `SUCCESS` or `FAILED`
* For completed templates, the response format changes to the full template object
* If a template doesn't exist and isn't in the creation queue, you'll receive a `404 Not Found` error

## Usage Example

Here's a complete example of checking template status:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    async function checkTemplateStatus(templateId) {
      const response = await fetch(
        `https://api.pdfnoodle.com/v1/integration/templates/${templateId}`,
        {
          headers: { Authorization: "Bearer pdfnoodle_api_123456789" },
        }
      );

      const data = await response.json();

      // Check if template is complete
      if (data.template) {
        console.log("Template is complete:", data.template);
        return data.template;
      }

      // Check creation status
      if (data.status === "SUCCESS") {
        console.log("Template created successfully!");
        console.log("Time to create:", data.metadata.timeToCreateTemplate);
        console.log("Template HTML:", data.templateHtml);
        console.log("PDF Preview:", data.pdfPreviewUrl);
        return data;
      } else if (data.status === "FAILED") {
        throw new Error(`Template creation failed: ${data.metadata.errorMessage}`);
      } else if (data.status === "ONGOING") {
        console.log("Template creation is still in progress...");
        return null; // Continue polling
      }
    }

    // Polling example
    async function pollTemplateStatus(templateId) {
      const maxAttempts = 40; // Poll for up to 10 minutes (40 * 15 seconds)
      let attempts = 0;

      while (attempts < maxAttempts) {
        const result = await checkTemplateStatus(templateId);

        if (result) {
          return result; // Template is ready or failed
        }

        // Wait 15 seconds before checking again
        await new Promise((resolve) => setTimeout(resolve, 15000));
        attempts++;
      }

      throw new Error("Template creation timed out");
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests
    import time

    def check_template_status(template_id):
        response = requests.get(
            f'https://api.pdfnoodle.com/v1/integration/templates/{template_id}',
            headers={'Authorization': 'Bearer pdfnoodle_api_123456789'}
        )

        data = response.json()

        # Check if template is complete
        if 'template' in data:
            print('Template is complete:', data['template'])
            return data['template']

        # Check creation status
        if data.get('status') == 'SUCCESS':
            print('Template created successfully!')
            print('Time to create:', data['metadata']['timeToCreateTemplate'])
            print('Template HTML:', data['templateHtml'])
            print('PDF Preview:', data['pdfPreviewUrl'])
            return data
        elif data.get('status') == 'FAILED':
            raise Exception(f"Template creation failed: {data['metadata']['errorMessage']}")
        elif data.get('status') == 'ONGOING':
            print('Template creation is still in progress...')
            return None  # Continue polling

    # Polling example
    def poll_template_status(template_id):
        max_attempts = 40  # Poll for up to 10 minutes (40 * 15 seconds)
        attempts = 0

        while attempts < max_attempts:
            result = check_template_status(template_id)

            if result:
                return result  # Template is ready or failed

            # Wait 15 seconds before checking again
            time.sleep(15)
            attempts += 1

        raise Exception('Template creation timed out')
    ```
  </Tab>
</Tabs>

## Error Responses

### 401 Unauthorized

```json theme={null}
{
  "message": "Unauthorized"
}
```

**Occurs when:** The API key is missing or invalid.

### 404 Not Found

```json theme={null}
{
  "message": "Couldnt find this template."
}
```

**Occurs when:** The requested template doesn't exist and isn't in the creation queue.

### 500 Internal Server Error

```json theme={null}
{
  "message": "Error message describing what went wrong"
}
```

**Occurs when:** An internal server error prevents the operation from completing.

<Warning>
  If the `status` is `FAILED`, check the `metadata.errorMessage` field for
  details about what went wrong. You may need to contact support if the error
  persists.
</Warning>
