> 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/guides/files-and-external-documents.md). Agents can also search and read this documentation through its [MCP server](https://developers.docstudio.com/~gitbook/mcp).

# Files and external documents

This document explains how to upload files and use them in DocStudio envelopes.

### Upload attachment

Use this endpoint to upload a new attachment.

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

### Headers

<table><thead><tr><th width="189.4444580078125">Header</th><th width="116.7777099609375">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>Authorization</code></td><td>Yes</td><td>Bearer authorization token</td></tr><tr><td><code>Content-Type</code></td><td>Yes</td><td>Use <code>multipart/form-data</code></td></tr><tr><td><code>Mailbox</code></td><td>No</td><td>Mailbox context header with the current mailbox UUID</td></tr></tbody></table>

### Query parameters

| Parameter | Type   | Required | Description                                                          |
| --------- | ------ | -------- | -------------------------------------------------------------------- |
| `type`    | string | No       | Uploaded file type: `all`, `document`, `file`, `image`, or `archive` |

Use `type` to specify the uploaded file category. Omit the parameter when no category is needed.

| Value      | Description              |
| ---------- | ------------------------ |
| `all`      | All supported file types |
| `document` | Document files           |
| `file`     | Files                    |
| `image`    | Image files              |
| `archive`  | Archive files            |

### Request body

The endpoint accepts `multipart/form-data`. The uploaded file must be passed in the required `file` field.

| Field  | Type   | Required | Description    |
| ------ | ------ | -------- | -------------- |
| `file` | binary | Yes      | File to upload |

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

```javascript
import { openAsBlob } from "node:fs";

const form = new FormData();
form.append("file", await openAsBlob("contract.pdf"), "contract.pdf");

const response = await fetch(
  "https://api.docstudio.com/api/v1/envelope/attachment?type=document",
  {
    method: "POST",
    headers: {
      Authorization: "Bearer {token}",
      Mailbox: "{mailboxUuid}"
    },
    body: form
  }
);

if (!response.ok) {
  throw new Error(`Upload failed: ${response.status}`);
}

console.log(await response.json());
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$curl = curl_init(
    "https://api.docstudio.com/api/v1/envelope/attachment?type=document"
);

curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer {token}",
        "Mailbox: {mailboxUuid}"
    ],
    CURLOPT_POSTFIELDS => [
        "file" => new CURLFile("contract.pdf", "application/pdf", "contract.pdf")
    ],
    CURLOPT_RETURNTRANSFER => true
]);

$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);

if ($status !== 201) {
    throw new RuntimeException("Upload failed: {$status}");
}

echo $body;
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

with open("contract.pdf", "rb") as file:
    response = requests.post(
        "https://api.docstudio.com/api/v1/envelope/attachment?type=document",
        headers={
            "Authorization": "Bearer {token}",
            "Mailbox": "{mailboxUuid}",
        },
        files={"file": ("contract.pdf", file, "application/pdf")},
        timeout=30,
    )

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

{% endtab %}

{% tab title="Ruby" %}

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

uri = URI(
  "https://api.docstudio.com/api/v1/envelope/attachment?type=document"
)
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer {token}"
request["Mailbox"] = "{mailboxUuid}"

request.set_form(
  [["file", File.open("contract.pdf", "rb"), { filename: "contract.pdf" }]],
  "multipart/form-data"
)

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

raise "Upload failed: #{response.code}" unless response.code == "201"

puts JSON.parse(response.body)
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	var body bytes.Buffer
	writer := multipart.NewWriter(&body)

	file, err := os.Open("contract.pdf")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	part, err := writer.CreateFormFile("file", "contract.pdf")
	if err != nil {
		panic(err)
	}

	if _, err := io.Copy(part, file); err != nil {
		panic(err)
	}

	if err := writer.Close(); err != nil {
		panic(err)
	}

	request, err := http.NewRequest(
		http.MethodPost,
		"https://api.docstudio.com/api/v1/envelope/attachment?type=document",
		&body,
	)
	if err != nil {
		panic(err)
	}

	request.Header.Set("Authorization", "Bearer {token}")
	request.Header.Set("Mailbox", "{mailboxUuid}")
	request.Header.Set("Content-Type", writer.FormDataContentType())

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

	if response.StatusCode != http.StatusCreated {
		panic(fmt.Sprintf("Upload failed: %s", response.Status))
	}

	fmt.Println(response.Status)
}
```

{% endtab %}

{% tab title="Java" %}

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

public class Main {
  public static void main(String[] args) throws Exception {
    String boundary = UUID.randomUUID().toString();
    Path file = Path.of("contract.pdf");
    String lineBreak = "\r\n";

    byte[] prefix = (
        "--" + boundary + lineBreak
            + "Content-Disposition: form-data; name=\"file\"; filename=\"contract.pdf\""
            + lineBreak
            + "Content-Type: application/pdf"
            + lineBreak + lineBreak
    ).getBytes();
    byte[] suffix = (lineBreak + "--" + boundary + "--" + lineBreak).getBytes();
    byte[] fileBytes = Files.readAllBytes(file);
    byte[] body = new byte[prefix.length + fileBytes.length + suffix.length];

    System.arraycopy(prefix, 0, body, 0, prefix.length);
    System.arraycopy(fileBytes, 0, body, prefix.length, fileBytes.length);
    System.arraycopy(suffix, 0, body, prefix.length + fileBytes.length, suffix.length);

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(
            "https://api.docstudio.com/api/v1/envelope/attachment?type=document"
        ))
        .header("Authorization", "Bearer {token}")
        .header("Mailbox", "{mailboxUuid}")
        .header("Content-Type", "multipart/form-data; boundary=" + boundary)
        .POST(HttpRequest.BodyPublishers.ofByteArray(body))
        .build();

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

    if (response.statusCode() != 201) {
      throw new RuntimeException("Upload failed: " + response.statusCode());
    }

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

{% endtab %}

{% tab title=".NET" %}

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

using var client = new HttpClient();
using var form = new MultipartFormDataContent();
using var file = File.OpenRead("contract.pdf");
using var content = new StreamContent(file);

content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
form.Add(content, "file", "contract.pdf");

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

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

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

Console.WriteLine(await response.Content.ReadAsStringAsync());
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl --request POST \
  --url 'https://api.docstudio.com/api/v1/envelope/attachment?type=document' \
  --header 'Authorization: Bearer {token}' \
  --header 'Mailbox: {mailboxUuid}' \
  --form 'file=@contract.pdf;type=application/pdf'
```

{% endtab %}
{% endtabs %}

### Response

The endpoint returns `201 Created` with information about the uploaded attachment.

```json
{
  "filename": "contract.pdf",
  "attachmentId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "filesize": 204800,
  "contentType": "application/pdf",
  "updatedPdf": "string"
}
```

<table><thead><tr><th width="161.2222900390625">Field</th><th width="163">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>filename</code></td><td>string</td><td>Uploaded file name</td></tr><tr><td><code>attachmentId</code></td><td>UUID</td><td>Uploaded attachment ID</td></tr><tr><td><code>filesize</code></td><td>integer</td><td>Uploaded file size in bytes</td></tr><tr><td><code>contentType</code></td><td>string</td><td>Uploaded file content type</td></tr><tr><td><code>updatedPdf</code></td><td>byte string</td><td>Updated PDF data, when included in the response</td></tr></tbody></table>

Save the `attachmentId` value from the response. This value is the uploaded file identifier that must be used later in envelope XML.

### Status codes

| Code | Description                      |
| ---- | -------------------------------- |
| 201  | Attachment uploaded successfully |

### Use the uploaded file in envelope XML

Pass `response.attachmentId` to the `attachmentUuid` attribute in envelope XML.

<table><thead><tr><th width="187.888916015625">Upload response field</th><th width="198.888916015625">Envelope XML attribute</th><th>Description</th></tr></thead><tbody><tr><td><code>attachmentId</code></td><td><code>attachmentUuid</code></td><td>Uploaded file ID returned by the upload endpoint and used as the uploaded file reference in envelope XML</td></tr><tr><td><code>filename</code></td><td>Field value</td><td>Uploaded file name, used as the field value when the template expects a visible file name</td></tr></tbody></table>

#### External document

Use this structure for an external document.

```xml
<document id="{documentId}" attachmentUuid="{attachmentId}" />
```

#### File upload field

Use this structure for a file upload field.

```xml
<document id="{documentId}">
  <field name="File" attachmentUuid="{attachmentId}">contract.pdf</field>
</document>
```

The field name must match the field name in the selected template. The document ID must also belong to the same template version that is used in the envelope request.

{% hint style="warning" %}
Use `multipart/form-data` and include the required `file` field. Pass the returned `attachmentId` to `attachmentUuid`. Do not use a local path, external URL, or generated UUID.
{% endhint %}

### Related topics

{% columns %}
{% column %}

* [Authentication and application tokens](https://developers.docstudio.com/introduction/authentication-and-application-tokens.md)
* [Working with XML payloads](https://developers.docstudio.com/guides/xml-payloads.md)
* [Working with templates and reusable IDs](https://developers.docstudio.com/guides/templates-and-reusable-ids.md)
  {% endcolumn %}

{% column %}

* [Working with envelope fields](https://developers.docstudio.com/guides/envelope-fields.md)
* [Send your first envelope](https://developers.docstudio.com/introduction/send-your-first-envelope.md)
* [Send Envelope](https://developers.docstudio.com/api-reference/send-envelope.md)
  {% endcolumn %}
  {% endcolumns %}
