> 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/examples/send-envelope-with-metadata.md). Agents can also search and read this documentation through its [MCP server](https://developers.docstudio.com/~gitbook/mcp).

# Send Envelope with Metadata

This document explains how to store and use envelope metadata through the API.

### Scenario

Send an envelope from a template and attach metadata for an external process.

### Step 1 Prepare template and metadata values

| Method | Endpoint                |
| ------ | ----------------------- |
| `POST` | `/api/v1/envelope/send` |

Prepare the template values and metadata before building the request.

You need:

{% columns %}
{% column %}

* API token
* sender mailbox UUID
* template UUID
* template version UUID
* role IDs from the template flow
  {% endcolumn %}

{% column %}

* recipient mailbox UUIDs
* document IDs from the template
* field names from the template
* metadata keys and values
  {% endcolumn %}
  {% endcolumns %}

#### Metadata rules

| Rule                  | Value                       |
| --------------------- | --------------------------- |
| Key length            | 1–32 characters             |
| Value length          | 0–128 characters            |
| Supported value types | `string`, `boolean`, `null` |

```json
{
  "customerId": "C-1024",
  "crmRecordId": "CRM-77551",
  "source": "crm",
  "priority": true,
  "externalReference": null
}
```

### Step 2 Build envelope XML

Build the envelope XML with template, role, document, and field values.

```xml
<envelope
  templateUuid="56cacd6a-ffe7-4b77-9c0c-f928d9a18cb5"
  templateVersion="ab0d11cb-ebdd-42bd-a581-ddca1bb9b585"
>
  <info>
    <subject>Sales agreement for ACME Ltd</subject>
    <message>Please review and complete the agreement.</message>
  </info>
  <flow>
    <roles>
      <role
        id="23f20eec-adad-4325-b553-1bde4be29198"
        mailboxUuid="9baec31c-e940-4894-b6d1-52033e1af66e"
      />
    </roles>
  </flow>
  <documents>
    <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
      <field name="customer_name">ACME Ltd</field>
      <field name="contract_amount">1250.50</field>
    </document>
  </documents>
</envelope>
```

Pass metadata in the `metadata` JSON object. Do not add it to the XML.

### Step 3 Send the request

Use these headers:

| Header          | Required | Description                |
| --------------- | -------- | -------------------------- |
| `Authorization` | Yes      | Bearer authorization token |
| `Content-Type`  | Yes      | Use `application/json`     |
| `Mailbox`       | Yes      | Sender mailbox UUID        |

Send the envelope XML in `data` and metadata in `metadata`.

```json
{
  "data": "<envelope templateUuid=\"56cacd6a-ffe7-4b77-9c0c-f928d9a18cb5\" templateVersion=\"ab0d11cb-ebdd-42bd-a581-ddca1bb9b585\">\n  <info>\n    <subject>Sales agreement for ACME Ltd</subject>\n    <message>Please review and complete the agreement.</message>\n  </info>\n  <flow>\n    <roles>\n      <role id=\"23f20eec-adad-4325-b553-1bde4be29198\" mailboxUuid=\"9baec31c-e940-4894-b6d1-52033e1af66e\" />\n    </roles>\n  </flow>\n  <documents>\n    <document id=\"4a61f258-fd9d-406c-b47e-81c90d4e5c47\">\n      <field name=\"customer_name\">ACME Ltd</field>\n      <field name=\"contract_amount\">1250.50</field>\n    </document>\n  </documents>\n</envelope>",
  "metadata": {
    "customerId": "C-1024",
    "crmRecordId": "CRM-77551",
    "source": "crm",
    "priority": true
  }
}
```

<table><thead><tr><th width="98">Field</th><th width="82">Type</th><th width="110">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>uuid</code></td><td>UUID</td><td>No</td><td>Envelope UUID when the flow already has an envelope identifier</td></tr><tr><td><code>data</code></td><td>string</td><td>Yes</td><td>Envelope XML string</td></tr><tr><td><code>metadata</code></td><td>object</td><td>No</td><td>Custom key-value metadata</td></tr></tbody></table>

### Request example

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

```javascript
const envelopeXml = "{envelopeXml}";

const metadata = {
  customerId: "C-1024",
  crmRecordId: "CRM-77551",
  source: "crm",
  priority: true
};

const response = await fetch(
  "https://api.docstudio.com/api/v1/envelope/send",
  {
    method: "POST",
    headers: {
      Authorization: "Bearer {token}",
      "Content-Type": "application/json",
      Mailbox: "{senderMailboxUuid}"
    },
    body: JSON.stringify({
      data: envelopeXml,
      metadata
    })
  }
);

const body = await response.text();

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

if (body) {
  console.log(body);
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$envelopeXml = "{envelopeXml}";

$payload = json_encode([
    "data" => $envelopeXml,
    "metadata" => [
        "customerId" => "C-1024",
        "crmRecordId" => "CRM-77551",
        "source" => "crm",
        "priority" => true
    ]
], JSON_THROW_ON_ERROR);

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

curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer {token}",
        "Content-Type: application/json",
        "Mailbox: {senderMailboxUuid}"
    ],
    CURLOPT_POSTFIELDS => $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}"
    );
}

if ($body !== "") {
    echo $body;
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

envelope_xml = "{envelopeXml}"

response = requests.post(
    "https://api.docstudio.com/api/v1/envelope/send",
    headers={
        "Authorization": "Bearer {token}",
        "Mailbox": "{senderMailboxUuid}",
    },
    json={
        "data": envelope_xml,
        "metadata": {
            "customerId": "C-1024",
            "crmRecordId": "CRM-77551",
            "source": "crm",
            "priority": True,
        },
    },
    timeout=30,
)

response.raise_for_status()

if response.text:
    print(response.text)
```

{% endtab %}

{% tab title="Ruby" %}

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

envelope_xml = "{envelopeXml}"

payload = {
  data: envelope_xml,
  metadata: {
    customerId: "C-1024",
    crmRecordId: "CRM-77551",
    source: "crm",
    priority: true
  }
}

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

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

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

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

puts response.body unless response.body.empty?
```

{% endtab %}

{% tab title="Go" %}

```go
package main

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

func main() {
	envelopeXML := "{envelopeXml}"

	payload := map[string]any{
		"data": envelopeXML,
		"metadata": map[string]any{
			"customerId": "C-1024",
			"crmRecordId": "CRM-77551",
			"source":      "crm",
			"priority":    true,
		},
	}

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

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

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

	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,
		))
	}

	if len(body) > 0 {
		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 payload = """
        {
          "data": "{envelopeXml}",
          "metadata": {
            "customerId": "C-1024",
            "crmRecordId": "CRM-77551",
            "source": "crm",
            "priority": true
          }
        }
        """;

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(
            "https://api.docstudio.com/api/v1/envelope/send"
        ))
        .header(
            "Authorization",
            "Bearer {token}"
        )
        .header(
            "Content-Type",
            "application/json"
        )
        .header(
            "Mailbox",
            "{senderMailboxUuid}"
        )
        .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()
      );
    }

    if (!response.body().isEmpty()) {
      System.out.println(response.body());
    }
  }
}
```

{% endtab %}

{% tab title=".NET" %}

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

var envelopeXml = "{envelopeXml}";

var payload = JsonSerializer.Serialize(new
{
    data = envelopeXml,
    metadata = new
    {
        customerId = "C-1024",
        crmRecordId = "CRM-77551",
        source = "crm",
        priority = true
    }
});

using var client = new HttpClient();

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

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

request.Content = new StringContent(
    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}"
    );
}

if (!string.IsNullOrEmpty(body))
{
    Console.WriteLine(body);
}
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl --request POST \
  --url 'https://api.docstudio.com/api/v1/envelope/send' \
  --header 'Authorization: Bearer {token}' \
  --header 'Content-Type: application/json' \
  --header 'Mailbox: {senderMailboxUuid}' \
  --data '{
    "data": "{envelopeXml}",
    "metadata": {
      "customerId": "C-1024",
      "crmRecordId": "CRM-77551",
      "source": "crm",
      "priority": true
    }
  }'
```

{% endtab %}
{% endtabs %}

### Step 4 Save the envelope UUID

The endpoint returns `201 Created`. Save the envelope UUID.

```json
{
  "uuid": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}
```

| Field  | Type | Description           |
| ------ | ---- | --------------------- |
| `uuid` | UUID | Created envelope UUID |

### Step 5 Manage metadata

#### Update metadata

Use this endpoint to add or change metadata.

| Method | Endpoint                         |
| ------ | -------------------------------- |
| `PUT`  | `/api/v1/envelope/{id}/metadata` |

Use these headers:

| Header          | Required | Description                |
| --------------- | -------- | -------------------------- |
| `Authorization` | Yes      | Bearer authorization token |
| `Content-Type`  | Yes      | Use `application/json`     |
| `Mailbox`       | Yes      | Current mailbox UUID       |

Path parameters:

| Parameter | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `id`      | UUID | Yes      | Envelope ID |

```json
{
  "crmRecordId": "CRM-77551",
  "processingStatus": "synced",
  "priority": true
}
```

The request adds new keys and overwrites existing values. The endpoint returns `200 OK`.

#### Read metadata

Read `envelope.metadata`.

```json
{
  "envelope": {
    "uuid": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "status": "WAITING",
    "metadata": {
      "customerId": "C-1024",
      "crmRecordId": "CRM-77551",
      "source": "crm",
      "priority": true
    }
  }
}
```

#### Display metadata

Add this element to the template info section:

```xml
<metadata show="true" />
```

{% hint style="info" %}
Display metadata only when the template includes this element and metadata has a value.
{% endhint %}

### Continue processing

Use the envelope UUID to check the envelope status, process callbacks, or download the completed archive.

{% hint style="warning" %}
Keep document values in fields and external references in metadata.

* Include the `Authorization` header
* Use the sender mailbox UUID in `Mailbox`
* Confirm token access to the sender mailbox
* Send valid envelope XML in `data`
* Send a valid JSON object in `metadata`
* Use keys that are 1–32 characters long
* Use values that are 0–128 characters long
* Use supported metadata value types
* Do not include secrets or large data blocks
* Add `<metadata show="true" />` to display metadata
  {% endhint %}
