> You are reading the Docusign Developer Documentation. For clean Markdown of any page, append .md to the page URL.
>
> Documentation indexes by section:
> - APIs and SDKs: https://docusign.docs.buildwithfern.com/docs/llms.txt
> - Platform 101: https://docusign.docs.buildwithfern.com/platform/llms.txt
> - Extension Apps: https://docusign.docs.buildwithfern.com/extension-apps/llms.txt
> - Docusign CLI: https://docusign.docs.buildwithfern.com/docusign-cli/llms.txt
>
> Authentication (OAuth, JWT Grant, M2M): https://docusign.docs.buildwithfern.com/platform/auth
> Webhooks and Connect: https://docusign.docs.buildwithfern.com/platform/webhooks
>
> OpenAPI specifications: https://docusign.docs.buildwithfern.com/openapi.json
> MCP server: https://docusign.docs.buildwithfern.com/_mcp/server

# How to download envelope documents

> Demonstrates how to programmatically download the documents associated with an envelope.

This topic demonstrates how to retrieve documents from an [envelope](/docs/esign-rest-api/esign101/concepts/envelopes), such as the generated Certificate of Completion (which is created when a document is completed), a composite PDF of all documents, a ZIP file containing everything, or a specific document within the envelope.

Before you download documents from an envelope, you will need to know the name or ID of the document that you want. You can get a [list of envelope documents](/docs/esign-rest-api/how-to/list-envelope-documents) to obtain this information.

> **Note**
>
> Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects: [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).

## Required data

Running the code in this how-to requires this data:

| Data element      | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| \{API_ACCOUNT_ID} | A [GUID](http://guid.one/) value that identifies your account. This value is automatically generated by Docusign for any account you create. Copy the value from the **API Account ID** field on the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=appsAndKeys) page.                                                                                                                                                                                                                                                                           |
| \{BASE_PATH}      | A string value that forms the root of the URL required to make API calls. The base path value in the example code is set to target the developer environment at https\://\<domain>/restapi Where \<domain> is demo.docusign.net for the developer environment and is the result of the GetUserInfo call in production.                                                                                                                                                                                                                                             |
| \{DOCUMENT_ID}    | A document identifier such as a name or ID. You can get a [list of envelope documents](/docs/esign-rest-api/how-to/list-envelope-documents) to obtain this information. **Note:** Replace this value with "combined" to obtain all the documents concatenated together, with "archive" to download a ZIP file including all the documents, with "certificate" to obtain the envelope's Certificate of Completion, or with "portfolio" to retrieve the envelope documents as a [PDF portfolio](https://helpx.adobe.com/acrobat/using/overview-pdf-portfolios.html). |
| \{ENVELOPE_ID}    | A [GUID](http://guid.one/) value that identifies a Docusign [envelope](/docs/esign-rest-api/esign101/concepts/envelopes). This value is automatically generated by Docusign when the envelope is created.                                                                                                                                                                                                                                                                                                                                                          |

## Step 1. Obtain your OAuth token

To make the API call shown in this how-to, you need a valid OAuth access token. Docusign supports access tokens for three different recommended OAuth grant types: Public Authorization Code Grant, Confidential Authorization Code Grant, and JSON Web Token (JWT) Grant. Choose the OAuth grant type appropriate for your scenario.

> **Note**
>
> See [Confidential Authorization Code Grant](/platform/auth/authcode#confidential-authorization-code-grant) for guidance on your options to get an Confidential Authorization Code Grant  OAuth token.

![Three icons that represent the three methods a user can use to obtain an OAuth token: JSON Web Token (JWT), Public Authorization Code Grant (ACG), and Confidential Authorization Code grant](/_fern-files/_img/64f473773042ee439449a096bf7673292b1585b86a4ccc55f82ba0dda41f61a1.webp)

## Step 2. Construct your API headers

After you have a valid OAuth access token, you are ready to construct the API headers that you will pass to the API call. Construct your headers like this, but make sure to substitute your valid OAuth access token for \{ACCESS_TOKEN}.

**`Bash`**

```bash title="Bash"
# Construct your API headers
declare -a Headers=('--header' "Authorization: Bearer ${ACCESS_TOKEN}" \
					'--header' "Accept: application/json" \
					'--header' "Content-Type: application/json")
```

**`C#`**

```csharp title="C#"
var docuSignClient = new DocuSignClient(basePath);
docuSignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
```

**`Java`**

```java title="Java"
ApiClient apiClient = new ApiClient(basePath);
apiClient.addDefaultHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTHENTICATION + userAccessToken);
```

**`Node.js`**

```javascript title="Node.js"
let dsApiClient = new docusign.ApiClient();
dsApiClient.setBasePath(args.basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
let envelopesApi = new docusign.EnvelopesApi(dsApiClient);
  let results = null;
```

**`PHP`**

```php title="PHP"
$config = new Configuration();
$config->setHost($args['base_path']);
$config->addDefaultHeader('Authorization', 'Bearer ' . $args['ds_access_token']);
$this->apiClient = new ApiClient($config);
```

**`PowerShell`**

```text title="PowerShell"
$headers = @{
    'Authorization' = "Bearer $accessToken";
    'Content-Type'  = "application/json";
  }
```

**`Python`**

```python title="Python"
api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
```

**`Ruby`**

```ruby title="Ruby"
configuration = DocuSign_eSign::Configuration.new
configuration.host = args[:base_path]
api_client = DocuSign_eSign::ApiClient.new configuration

api_client.default_headers['Authorization'] = "Bearer #{args[:access_token]}"
```

## Step 3. Call the eSignature REST API

Now that you have constructed your API headers, make a request to the eSignature REST API [EnvelopeDocuments:get](/docs/esign-rest-api/reference/envelopes/envelopedocuments/get)

endpoint to download the document or documents you want. Here’s how you make the call, but make sure to substitute your API account ID for \{ACCOUNT_ID}, envelope ID for \{ENVELOPE_ID}, and document ID for \{DOCUMENT_ID}.

The document ID specifies the document or documents that you want to download. You can use the document ID itself or one of the following keywords.

* `combined`: Retrieves a PDF file that contains the combined content of all of the documents. If the account option **Attach certification of completion to envelope** is on, then the Certificate of Completion is also included in the PDF file. You set this account option in the Admin tool on the **Signing Settings** screen, or by setting the `attachCompletedEnvelope` property in the `accountSettings` object to `true`.
* `archive`: Retrieves a ZIP archive that contains all of the PDF documents and the Certificate of Completion.
* `certificate`: Retrieves the Certificate of Completion as a PDF file.
* `portfolio`: Retrieves the envelope documents as a [PDF portfolio](https://helpx.adobe.com/acrobat/using/overview-pdf-portfolios.html).

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/eSignature/eg007EnvelopeGetDoc.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/eSignature/Examples/GetDocumentFromEnvelope.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/eSignature/services/EnvelopeGetDocService.java), [Node.js](https://github.com/docusign/code-examples-node/blob/master/lib/eSignature/examples/envelopeGetDoc.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Services/Examples/eSignature/EnvelopeGetDocService.php), [PowerShell](https://github.com/docusign/code-examples-powershell/blob/master/examples/eSignature/eg007EnvelopeGetDoc.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/eSignature/examples/eg007_envelope_get_doc.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/main/app/services/e_sign/eg007_envelope_get_doc_service.rb).

**`Bash`**

```bash title="Bash"
Status=$(curl -w '%{http_code}' -i --request GET ${base_path}/v2.1/accounts/${account_id}/envelopes/${envelope_id}/documents/${doc_choice} \
     "${Headers[@]}" \
     --output ${output_file}${output_file_extension})
```

**`C#`**

```csharp title="C#"
EnvelopesApi envelopesApi = new EnvelopesApi(docuSignClient);

// Step 1. EnvelopeDocuments::get.
// Exceptions will be caught by the calling function
var results = envelopesApi.GetDocumentWithHttpInfo(accountId, envelopeId, documentId);
results.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
results.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}

// Step 2. Look up the document from the list of documents
EnvelopeDocItem docItem = documents.FirstOrDefault(d => documentId.Equals(d.DocumentId));
```

**`Java`**

```java title="Java"
var documentResponse = envelopesApi.getDocumentWithHttpInfo(accountId, envelopeId, documentId,
        envelopesApi.new GetDocumentOptions());
Map<String, List<String>> headers = documentResponse.getHeaders();
java.util.List<String> remaining = headers.get("X-RateLimit-Remaining");
java.util.List<String> reset = headers.get("X-RateLimit-Reset");

if (remaining != null & reset != null) {
    Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
    System.out.println("API calls remaining: " + remaining);
    System.out.println("Next Reset: " + resetInstant);
}
return documentResponse.getData();
```

**`Node.js`**

```javascript title="Node.js"
results = await envelopesApi.getDocument(
  args.accountId,
  args.envelopeDocuments.envelopeId,
  args.documentId,
  null,
  (error, data, response) => {
    const headers = response?.headers;

    const remaining = headers?.['x-ratelimit-remaining'];
    const reset = headers?.['x-ratelimit-reset'];

    if (remaining && reset) {
      const resetInstant = new Date(Number(reset) * 1000);

      console.log(`API calls remaining: ${remaining}`);
      console.log(`Next Reset: ${resetInstant.toISOString()}`);
    }
});
var fileBytes = results.data;
```

**`PHP`**

```php title="PHP"
$envelope_api = $clientService->getEnvelopeApi();

# An SplFileObject is returned. See http://php.net/manual/en/class.splfileobject.php
$temp_file = $envelope_api->getDocumentWithHttpInfo($args['account_id'], $args['document_id'], $args['envelope_id']);

$remaining = $temp_file[2]['X-RateLimit-Remaining'] ?? null;
$reset = $temp_file[2]['X-RateLimit-Reset'] ?? null;

if ($remaining !== null && $reset !== null) {
    $resetInstant = (new DateTime())->setTimestamp((int)$reset);
    error_log("API calls remaining: $remaining");
    error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
}
```

**`PowerShell`**

```text title="PowerShell"
Invoke-RestMethod `
    -Uri "${apiUri}/v2.1/accounts/${accountId}/envelopes/${envelopeId}/documents/${docChoice}" `
    -Method 'GET' `
    -Headers $headers `
    -OutFile ${outputFile}${outputFileExtension}
```

**`Python`**

```python title="Python"
envelope_api = EnvelopesApi(api_client)
document_id = args["document_id"]

# Call the envelope get method to get the path of the temp file with the documents
(document_bytes, status, headers) = envelope_api.get_document_with_http_info(
    account_id=args["account_id"],
    document_id=document_id,
    envelope_id=args["envelope_id"]
)

remaining = headers.get("X-RateLimit-Remaining")
reset = headers.get("X-RateLimit-Reset")

if remaining is not None and reset is not None:
    reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
    print(f"API calls remaining: {remaining}")
    print(f"Next Reset: {reset_date}")
```

**`Ruby`**

```ruby title="Ruby"
envelope_api = create_envelope_api(args)

document_id = args[:document_id]

temp_file, _status, headers = envelope_api.get_document_with_http_info args[:account_id], document_id, args[:envelope_id]

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end
```

## Expected response

You should receive the Certificate of Completion, a composite PDF of all documents, a ZIP file containing everything, or a specific document within the envelope.

## Next steps

* Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects:    [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).
* See complete documentation of the [EnvelopeDocuments:get](/docs/esign-rest-api/reference/envelopes/envelopedocuments/get) endpoint in the API Reference.
* Learn more about [documents](/docs/esign-rest-api/esign101/concepts/documents) or [envelopes](/docs/esign-rest-api/esign101/concepts/envelopes).
* See how to [Go-Live](/docs/esign-rest-api/go-live) with a completed app and find the base path for API calls in the production environment.