> ## 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.

# Create Template with AI

> Creates a new template using AI based on a text prompt and optional file reference. This is an asynchronous operation that typically takes a couple of minutes to complete.

<Note>
  Template creation is processed asynchronously. The endpoint returns
  immediately with a `templateId` that you can use to check the creation status.
  Template creation usually takes a couple of minutes, but can vary based on
  complexity and system load.
</Note>

POST [https://api.pdfnoodle.com/v1/integration/templates/create](https://api.pdfnoodle.com/v1/integration/templates/create)

## Request

<CodeGroup>
  ```bash cURL theme={null}
  curl --location 'https://api.pdfnoodle.com/v1/integration/templates/create' \
  --header 'Authorization: Bearer pdfnoodle_api_123456789' \
  --header 'Content-Type: application/json' \
  --data '{
      "prompt": "Create an invoice template with company logo, billing address, line items table, and total amount",
      "displayName": "Standard Invoice",
      "fileUrl": "https://example.com/reference-invoice.pdf"
  }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    "https://api.pdfnoodle.com/v1/integration/templates/create",
    {
      method: "POST",
      headers: {
        Authorization: "Bearer pdfnoodle_api_123456789",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        prompt:
          "Create an invoice template with company logo, billing address, line items table, and total amount",
        displayName: "Standard Invoice",
        fileUrl: "https://example.com/reference-invoice.pdf",
      }),
    }
  );

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

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

  response = requests.post(
      'https://api.pdfnoodle.com/v1/integration/templates/create',
      headers={
          'Authorization': 'Bearer pdfnoodle_api_123456789',
          'Content-Type': 'application/json'
      },
      json={
          'prompt': 'Create an invoice template with company logo, billing address, line items table, and total amount',
          'displayName': 'Standard Invoice',
          'fileUrl': 'https://example.com/reference-invoice.pdf'
      }
  )

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

## Response

<CodeGroup>
  ```json Success (202 Accepted) theme={null}
  {
    "message": "Async template creation started. It usually takes a couple of minutes to finish creation. You can check the status of the template creation by fetching it using the templateId.",
    "fetchTemplateUrl": "https://api.pdfnoodle.com/v1/integration/templates/a1b2c3d4e5",
    "templateId": "a1b2c3d4e5"
  }
  ```
</CodeGroup>

This endpoint responds with `202 Accepted` immediately after starting the template creation process. The response includes a `templateId` that you can use to check the creation status.

## Parameters

<ParamField body="prompt" type="string" required>
  Text description of the template you want to create. This will be enriched by
  AI to generate the final template. Provide detailed, specific prompts for
  better results. Include information about: - Document type (invoice, receipt,
  report, etc.) - Required sections (header, footer, body content) - Layout
  preferences - Data fields that need to be included
</ParamField>

<ParamField body="displayName" type="string" required>
  Human-readable name for the template (e.g., "Invoice Template", "Receipt
  Template")
</ParamField>

<ParamField body="fileUrl" type="string">
  Optional URL to a reference file (PDF, image, etc.) that the AI can use as
  inspiration for the template design. This can help the AI understand your
  design preferences if you have an existing document to reference.
</ParamField>

## Response Fields

<ParamField response="message" type="string">
  Informational message about the async template creation process
</ParamField>

<ParamField response="fetchTemplateUrl" type="string">
  URL endpoint you can use to check the status of the template creation. Replace
  `{templateId}` with the actual `templateId` value.
</ParamField>

<ParamField response="templateId" type="string">
  A randomly generated 10-character hexadecimal string that uniquely identifies
  the template within your company context. Use this value to check the creation
  status and fetch the template once it's ready.
</ParamField>

## Checking Template Creation Status

After creating a template, you can check its status by polling the [Get Template](/api-reference/templates/get-template) endpoint using the `templateId` returned from this request.

The template will have different status values:

* **`ONGOING`**: Template creation is still in progress
* **`SUCCESS`**: Template has been created successfully
* **`FAILED`**: Template creation failed (check `metadata.errorMessage`)

## Usage Example

Here's a complete example of creating a template and polling for completion:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    async function createTemplate(prompt, displayName, fileUrl) {
      // 1. Create template
      const createResponse = await fetch(
        "https://api.pdfnoodle.com/v1/integration/templates/create",
        {
          method: "POST",
          headers: {
            Authorization: "Bearer pdfnoodle_api_123456789",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            prompt,
            displayName,
            fileUrl,
          }),
        }
      );

      const { templateId, fetchTemplateUrl } = await createResponse.json();

      // 2. Poll for completion
      let templateReady = false;
      while (!templateReady) {
        await new Promise((resolve) => setTimeout(resolve, 15000)); // Wait 15 seconds

        const statusResponse = await fetch(
          `https://api.pdfnoodle.com/v1/integration/templates/${templateId}`,
          {
            headers: { Authorization: "Bearer pdfnoodle_api_123456789" },
          }
        );

        const data = await statusResponse.json();

        if (data.template) {
          // Template is complete
          templateReady = true;
          console.log("Template ready:", data.template);
          return data.template;
        } else if (data.status === "SUCCESS") {
          // Template creation completed
          templateReady = true;
          console.log("Template created:", data.templateHtml);
          return data;
        } else if (data.status === "FAILED") {
          // Template creation failed
          throw new Error(data.metadata.errorMessage);
        }
        // Otherwise, status is 'ONGOING', continue polling
      }
    }

    // Usage
    createTemplate(
      "Create an invoice template with company logo, billing address, line items table, and total amount",
      "Standard Invoice"
    );
    ```
  </Tab>

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

    def create_template(prompt, display_name, file_url=None):
        # 1. Create template
        response = requests.post(
            'https://api.pdfnoodle.com/v1/integration/templates/create',
            headers={
                'Authorization': 'Bearer pdfnoodle_api_123456789',
                'Content-Type': 'application/json'
            },
            json={
                'prompt': prompt,
                'displayName': display_name,
                'fileUrl': file_url
            }
        )

        result = response.json()
        template_id = result['templateId']

        # 2. Poll for completion
        template_ready = False
        while not template_ready:
            time.sleep(15)  # Wait 15 seconds

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

            data = status_response.json()

            if 'template' in data:
                # Template is complete
                template_ready = True
                print('Template ready:', data['template'])
                return data['template']
            elif data.get('status') == 'SUCCESS':
                # Template creation completed
                template_ready = True
                print('Template created:', data['templateHtml'])
                return data
            elif data.get('status') == 'FAILED':
                # Template creation failed
                raise Exception(data['metadata']['errorMessage'])
            # Otherwise, status is 'ONGOING', continue polling

    # Usage
    create_template(
        'Create an invoice template with company logo, billing address, line items table, and total amount',
        'Standard Invoice'
    )
    ```
  </Tab>
</Tabs>

<Warning>
  If template creation fails, the status will be set to `FAILED` and error
  details will be available in the metadata when fetching the template. You
  should handle these errors appropriately in your application.
</Warning>

## Error Responses

### 401 Unauthorized

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

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

### 500 Internal Server Error

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

**Occurs when:** An internal server error prevents the template creation from starting.
