> For the complete documentation index, see [llms.txt](https://developers.docstudio.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.docstudio.com/api-reference/create-template.md). Agents can also search and read this documentation through its [MCP server](https://developers.docstudio.com/~gitbook/mcp).

# Create Template

This document contains details for the /api/v1/template endpoint, including headers, request body, response fields, and status codes.

### Endpoint

| Method | Endpoint           |
| ------ | ------------------ |
| `POST` | `/api/v1/template` |

### Headers

| Header          | Required | Description                |
| --------------- | -------- | -------------------------- |
| `Authorization` | Yes      | Bearer authorization token |
| `Content-Type`  | Yes      | `application/json`         |
| `mailboxUuid`   | Yes      | Target mailbox UUID        |

### Request body

<table><thead><tr><th width="126.6666259765625">Field</th><th width="117.5555419921875">Type</th><th width="110.3333740234375">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>access</code></td><td>string</td><td>Yes</td><td>Template access level, such as <code>mailbox</code></td></tr><tr><td><code>categories</code></td><td>array</td><td>Yes</td><td>Category IDs, or an empty array</td></tr><tr><td><code>data</code></td><td>string</td><td>Yes</td><td>Template XML serialized as a JSON string</td></tr></tbody></table>

### Request example

{% tabs %}
{% tab title="Node.js" %}

```javascript
const templateXml = `
<template>
  <info>
    <name>Sales agreement</name>
    <description>Template for sales agreement envelopes</description>
    <subject>Sales agreement</subject>
    <message>Please review and complete the agreement.</message>
  </info>
  <flow>
    <roles>
      <role
        id="23f20eec-adad-4325-b553-1bde4be29198"
        title="Sender"
        type="sender"
        order="0"
      />
      <role
        id="b811f2b6-1656-42aa-9420-a9b8addb0246"
        title="Assignee"
        type="assignee"
        order="1"
      />
    </roles>
  </flow>
  <documents>
    <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
      <info>
        <title>Agreement</title>
      </info>
      <body>
        <field
          type="text"
          name="customer_name"
          placeholder="Enter customer name"
          roleId="b811f2b6-1656-42aa-9420-a9b8addb0246"
          optional="false"
        />
      </body>
    </document>
  </documents>
</template>
`.trim();

const payload = {
  access: "mailbox",
  categories: [],
  data: templateXml
};

const response = await fetch(
  "https://api.docstudio.com/api/v1/template",
  {
    method: "POST",
    headers: {
      Authorization: "Bearer {token}",
      mailboxUuid: "{mailboxUuid}",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(payload)
  }
);

const body = await response.text();

if (!response.ok) {
  throw new Error(
    `Request failed: ${response.status}\n${body}`
  );
}

console.log(body);
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$templateXml = <<<'XML'
<template>
  <info>
    <name>Sales agreement</name>
    <description>Template for sales agreement envelopes</description>
    <subject>Sales agreement</subject>
    <message>Please review and complete the agreement.</message>
  </info>
  <flow>
    <roles>
      <role
        id="23f20eec-adad-4325-b553-1bde4be29198"
        title="Sender"
        type="sender"
        order="0"
      />
      <role
        id="b811f2b6-1656-42aa-9420-a9b8addb0246"
        title="Assignee"
        type="assignee"
        order="1"
      />
    </roles>
  </flow>
  <documents>
    <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
      <info>
        <title>Agreement</title>
      </info>
      <body>
        <field
          type="text"
          name="customer_name"
          placeholder="Enter customer name"
          roleId="b811f2b6-1656-42aa-9420-a9b8addb0246"
          optional="false"
        />
      </body>
    </document>
  </documents>
</template>
XML;

$payload = [
    "access" => "mailbox",
    "categories" => [],
    "data" => $templateXml
];

$curl = curl_init(
    "https://api.docstudio.com/api/v1/template"
);

curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer {token}",
        "mailboxUuid: {mailboxUuid}",
        "Content-Type: application/json"
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_RETURNTRANSFER => true
]);

$body = curl_exec($curl);

if ($body === false) {
    throw new RuntimeException(curl_error($curl));
}

$status = curl_getinfo(
    $curl,
    CURLINFO_RESPONSE_CODE
);

curl_close($curl);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException(
        "Request failed: {$status}\n{$body}"
    );
}

echo $body;
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

template_xml = """
<template>
  <info>
    <name>Sales agreement</name>
    <description>Template for sales agreement envelopes</description>
    <subject>Sales agreement</subject>
    <message>Please review and complete the agreement.</message>
  </info>
  <flow>
    <roles>
      <role
        id="23f20eec-adad-4325-b553-1bde4be29198"
        title="Sender"
        type="sender"
        order="0"
      />
      <role
        id="b811f2b6-1656-42aa-9420-a9b8addb0246"
        title="Assignee"
        type="assignee"
        order="1"
      />
    </roles>
  </flow>
  <documents>
    <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
      <info>
        <title>Agreement</title>
      </info>
      <body>
        <field
          type="text"
          name="customer_name"
          placeholder="Enter customer name"
          roleId="b811f2b6-1656-42aa-9420-a9b8addb0246"
          optional="false"
        />
      </body>
    </document>
  </documents>
</template>
""".strip()

response = requests.post(
    "https://api.docstudio.com/api/v1/template",
    headers={
        "Authorization": "Bearer {token}",
        "mailboxUuid": "{mailboxUuid}",
    },
    json={
        "access": "mailbox",
        "categories": [],
        "data": template_xml,
    },
    timeout=30,
)

response.raise_for_status()
print(response.json())
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
require "json"
require "net/http"
require "uri"

template_xml = <<~XML.strip
  <template>
    <info>
      <name>Sales agreement</name>
      <description>Template for sales agreement envelopes</description>
      <subject>Sales agreement</subject>
      <message>Please review and complete the agreement.</message>
    </info>
    <flow>
      <roles>
        <role
          id="23f20eec-adad-4325-b553-1bde4be29198"
          title="Sender"
          type="sender"
          order="0"
        />
        <role
          id="b811f2b6-1656-42aa-9420-a9b8addb0246"
          title="Assignee"
          type="assignee"
          order="1"
        />
      </roles>
    </flow>
    <documents>
      <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
        <info>
          <title>Agreement</title>
        </info>
        <body>
          <field
            type="text"
            name="customer_name"
            placeholder="Enter customer name"
            roleId="b811f2b6-1656-42aa-9420-a9b8addb0246"
            optional="false"
          />
        </body>
      </document>
    </documents>
  </template>
XML

uri = URI(
  "https://api.docstudio.com/api/v1/template"
)

payload = {
  access: "mailbox",
  categories: [],
  data: template_xml
}

request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer {token}"
request["mailboxUuid"] = "{mailboxUuid}"
request["Content-Type"] = "application/json"
request.body = JSON.generate(payload)

response = Net::HTTP.start(
  uri.hostname,
  uri.port,
  use_ssl: true
) do |http|
  http.request(request)
end

unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed: #{response.code}\n#{response.body}"
end

puts response.body
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func main() {
	templateXML := `<template>
  <info>
    <name>Sales agreement</name>
    <description>Template for sales agreement envelopes</description>
    <subject>Sales agreement</subject>
    <message>Please review and complete the agreement.</message>
  </info>
  <flow>
    <roles>
      <role
        id="23f20eec-adad-4325-b553-1bde4be29198"
        title="Sender"
        type="sender"
        order="0"
      />
      <role
        id="b811f2b6-1656-42aa-9420-a9b8addb0246"
        title="Assignee"
        type="assignee"
        order="1"
      />
    </roles>
  </flow>
  <documents>
    <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
      <info>
        <title>Agreement</title>
      </info>
      <body>
        <field
          type="text"
          name="customer_name"
          placeholder="Enter customer name"
          roleId="b811f2b6-1656-42aa-9420-a9b8addb0246"
          optional="false"
        />
      </body>
    </document>
  </documents>
</template>`

	payload := map[string]any{
		"access":     "mailbox",
		"categories": []string{},
		"data":       templateXML,
	}

	requestBody, err := json.Marshal(payload)
	if err != nil {
		panic(err)
	}

	request, err := http.NewRequest(
		http.MethodPost,
		"https://api.docstudio.com/api/v1/template",
		bytes.NewReader(requestBody),
	)
	if err != nil {
		panic(err)
	}

	request.Header.Set(
		"Authorization",
		"Bearer {token}",
	)
	request.Header.Set(
		"mailboxUuid",
		"{mailboxUuid}",
	)
	request.Header.Set(
		"Content-Type",
		"application/json",
	)

	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}

	if response.StatusCode < 200 ||
		response.StatusCode >= 300 {
		panic(fmt.Sprintf(
			"Request failed: %s\n%s",
			response.Status,
			body,
		))
	}

	fmt.Println(string(body))
}
```

{% endtab %}

{% tab title="Java" %}

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
  public static void main(String[] args) throws Exception {
    String templateXml = """
        <template>
          <info>
            <name>Sales agreement</name>
            <description>Template for sales agreement envelopes</description>
            <subject>Sales agreement</subject>
            <message>Please review and complete the agreement.</message>
          </info>
          <flow>
            <roles>
              <role
                id="23f20eec-adad-4325-b553-1bde4be29198"
                title="Sender"
                type="sender"
                order="0"
              />
              <role
                id="b811f2b6-1656-42aa-9420-a9b8addb0246"
                title="Assignee"
                type="assignee"
                order="1"
              />
            </roles>
          </flow>
          <documents>
            <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
              <info>
                <title>Agreement</title>
              </info>
              <body>
                <field
                  type="text"
                  name="customer_name"
                  placeholder="Enter customer name"
                  roleId="b811f2b6-1656-42aa-9420-a9b8addb0246"
                  optional="false"
                />
              </body>
            </document>
          </documents>
        </template>
        """.trim();

    String escapedTemplateXml = templateXml
        .replace("\\", "\\\\")
        .replace("\"", "\\\"")
        .replace("\r", "\\r")
        .replace("\n", "\\n");

    String payload = """
        {
          "access": "mailbox",
          "categories": [],
          "data": "%s"
        }
        """.formatted(escapedTemplateXml);

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(
            "https://api.docstudio.com/api/v1/template"
        ))
        .header(
            "Authorization",
            "Bearer {token}"
        )
        .header(
            "mailboxUuid",
            "{mailboxUuid}"
        )
        .header(
            "Content-Type",
            "application/json"
        )
        .POST(
            HttpRequest.BodyPublishers.ofString(payload)
        )
        .build();

    HttpResponse<String> response =
        HttpClient.newHttpClient().send(
            request,
            HttpResponse.BodyHandlers.ofString()
        );

    if (response.statusCode() < 200 ||
        response.statusCode() >= 300) {
      throw new RuntimeException(
          "Request failed: " +
          response.statusCode() +
          "\n" +
          response.body()
      );
    }

    System.out.println(response.body());
  }
}
```

{% endtab %}

{% tab title=".NET" %}

```csharp
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

var templateXml = """
<template>
  <info>
    <name>Sales agreement</name>
    <description>Template for sales agreement envelopes</description>
    <subject>Sales agreement</subject>
    <message>Please review and complete the agreement.</message>
  </info>
  <flow>
    <roles>
      <role
        id="23f20eec-adad-4325-b553-1bde4be29198"
        title="Sender"
        type="sender"
        order="0"
      />
      <role
        id="b811f2b6-1656-42aa-9420-a9b8addb0246"
        title="Assignee"
        type="assignee"
        order="1"
      />
    </roles>
  </flow>
  <documents>
    <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
      <info>
        <title>Agreement</title>
      </info>
      <body>
        <field
          type="text"
          name="customer_name"
          placeholder="Enter customer name"
          roleId="b811f2b6-1656-42aa-9420-a9b8addb0246"
          optional="false"
        />
      </body>
    </document>
  </documents>
</template>
""";

var payload = new
{
    access = "mailbox",
    categories = Array.Empty<string>(),
    data = templateXml
};

using var client = new HttpClient();

using var request = new HttpRequestMessage(
    HttpMethod.Post,
    "https://api.docstudio.com/api/v1/template"
);

request.Headers.Authorization =
    new AuthenticationHeaderValue(
        "Bearer",
        "{token}"
    );

request.Headers.Add(
    "mailboxUuid",
    "{mailboxUuid}"
);

request.Content = new StringContent(
    JsonSerializer.Serialize(payload),
    Encoding.UTF8,
    "application/json"
);

using var response =
    await client.SendAsync(request);

var body =
    await response.Content.ReadAsStringAsync();

if (!response.IsSuccessStatusCode)
{
    throw new HttpRequestException(
        $"Request failed: " +
        $"{(int)response.StatusCode}\n{body}"
    );
}

Console.WriteLine(body);
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl --request POST \
  --url 'https://api.docstudio.com/api/v1/template' \
  --header 'Authorization: Bearer {token}' \
  --header 'mailboxUuid: {mailboxUuid}' \
  --header 'Content-Type: application/json' \
  --data '{
    "access": "mailbox",
    "categories": [],
    "data": "<template><info><name>Sales agreement</name><description>Template for sales agreement envelopes</description><subject>Sales agreement</subject><message>Please review and complete the agreement.</message></info><flow><roles><role id=\"23f20eec-adad-4325-b553-1bde4be29198\" title=\"Sender\" type=\"sender\" order=\"0\"/><role id=\"b811f2b6-1656-42aa-9420-a9b8addb0246\" title=\"Assignee\" type=\"assignee\" order=\"1\"/></roles></flow><documents><document id=\"4a61f258-fd9d-406c-b47e-81c90d4e5c47\"><info><title>Agreement</title></info><body><field type=\"text\" name=\"customer_name\" placeholder=\"Enter customer name\" roleId=\"b811f2b6-1656-42aa-9420-a9b8addb0246\" optional=\"false\"/></body></document></documents></template>"
  }'
```

{% endtab %}
{% endtabs %}

### Response

<table><thead><tr><th>Field</th><th width="231">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>uuid</code></td><td>UUID</td><td>Created template UUID</td></tr><tr><td><code>version</code></td><td>UUID</td><td>Created template version UUID</td></tr></tbody></table>

### Response example

```json
{
  "uuid": "56cacd6a-ffe7-4b77-9c0c-f928d9a18cb5",
  "version": "ab0d11cb-ebdd-42bd-a581-ddca1bb9b585"
}
```

### Status codes

<table><thead><tr><th width="180.6666259765625">Code</th><th>Description</th></tr></thead><tbody><tr><td><code>200</code></td><td>Success. The response contains the template UUID and version</td></tr><tr><td><code>401</code></td><td>Missing, invalid, or expired authorization token</td></tr><tr><td><code>403</code></td><td>Authenticated user cannot create templates in the target mailbox</td></tr></tbody></table>

### Related topics

* [Send Envelope](https://developers.docstudio.com/api-reference/send-envelope.md)
* [Fill Envelope](https://developers.docstudio.com/api-reference/fill-envelope.md)
