# Download Document

This endpoint returns the raw binary file data with appropriate Content-Type headers for direct file download or display in applications

**Endpoint**

`GET/v2/customer/{customerId}/file/{id}`

**Link**

{% embed url="<https://stagep.tst-apidmndelss.com/openapi/v2.html#/operations/Customer_DocumentDownload>" %}

### **Request**

#### **Path Parameters**

| Parameter        | Type     | Description                             | Required | Example        |
| ---------------- | -------- | --------------------------------------- | -------- | -------------- |
| **`customerId`** | `string` | **Customer ID** that owns the document. | Yes      | `"cust_12345"` |
| **`id`**         | `string` | **Document unique ID** to download.     | Yes      | `"doc_abc123"` |

#### **Headers**

| Key                 | Value                       | Required |
| ------------------- | --------------------------- | -------- |
| **`Authorization`** | `123`                       | Yes      |
| **`Accept`**        | `*/*` or specific MIME type | No       |

***

### **Response (200 OK)**

Returns the raw binary file content with appropriate HTTP headers for file download.

#### **Response Headers**

| Header                    | Description               | Example                               |
| ------------------------- | ------------------------- | ------------------------------------- |
| **`Content-Type`**        | MIME type of the document | `application/pdf`                     |
| **`Content-Length`**      | File size in bytes        | `2048576`                             |
| **`Content-Disposition`** | File download behavior    | `attachment; filename="passport.pdf"` |
| **`Cache-Control`**       | Caching directives        | `private, max-age=3600`               |

#### **Response Body**

Raw binary content of the requested document file.

***

### **Examples**

#### **Request**

bash

```
curl -X GET 'https://stagep.tst-apidmndelss.com/v2/customer/cust_12345/file/doc_abc123' \
  -H 'Authorization: 123' \
  -H 'Accept: application/pdf' \
  --output downloaded_document.pdf
```

#### **PDF Document Download Example**

**Request:**

bash

```
curl -X GET 'https://stagep.tst-apidmndelss.com/v2/customer/cust_12345/file/doc_pass123' \
  -H 'Authorization: 123' \
  --output passport.pdf
```

**Response Headers:**

text

```
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 3120450
Content-Disposition: attachment; filename="us_passport.pdf"
Cache-Control: private, max-age=3600
```

**Response Body:** Raw PDF binary data

#### **Image Document Download Example**

**Request:**

bash

```
curl -X GET 'https://stagep.tst-apidmndelss.com/v2/customer/cust_67890/file/doc_util456' \
  -H 'Authorization: 123' \
  --output utility_bill.jpg
```

**Response Headers:**

text

```
HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: 1856320
Content-Disposition: attachment; filename="electricity_bill.jpg"
Cache-Control: private, max-age=3600
```

**Response Body:** Raw JPEG binary data

#### **Programming Language Examples**

**Python Download Example**

python

```
import requests

def download_document(customer_id, document_id, auth_token, output_path):
    url = f"https://stagep.tst-apidmndelss.com/v2/customer/{customer_id}/file/{document_id}"
    headers = {
        "Authorization": auth_token
    }
    
    response = requests.get(url, headers=headers, stream=True)
    
    if response.status_code == 200:
        # Get filename from Content-Disposition header or use document ID
        content_disposition = response.headers.get('Content-Disposition')
        if content_disposition and 'filename=' in content_disposition:
            filename = content_disposition.split('filename=')[1].strip('"')
        else:
            filename = f"{document_id}.{response.headers['Content-Type'].split('/')[1]}"
        
        with open(output_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)
        
        print(f"Document downloaded successfully: {filename}")
        print(f"File size: {response.headers.get('Content-Length')} bytes")
        print(f"Content type: {response.headers.get('Content-Type')}")
    else:
        print(f"Error downloading document: {response.status_code} - {response.text}")

# Usage
download_document("cust_12345", "doc_pass123", "123", "downloaded_passport.pdf")
```

**JavaScript/Node.js Download Example**

javascript

```
const https = require('https');
const fs = require('fs');

function downloadDocument(customerId, documentId, authToken, outputPath) {
    const options = {
        hostname: 'stagep.tst-apidmndelss.com',
        path: `/v2/customer/${customerId}/file/${documentId}`,
        method: 'GET',
        headers: {
            'Authorization': authToken
        }
    };

    const request = https.request(options, (response) => {
        if (response.statusCode === 200) {
            const fileStream = fs.createWriteStream(outputPath);
            response.pipe(fileStream);
            
            fileStream.on('finish', () => {
                fileStream.close();
                console.log('Document downloaded successfully');
                console.log(`Content-Type: ${response.headers['content-type']}`);
                console.log(`Content-Length: ${response.headers['content-length']} bytes`);
            });
        } else {
            console.error(`Error: ${response.statusCode}`);
        }
    });

    request.on('error', (error) => {
        console.error('Request error:', error);
    });

    request.end();
}

// Usage
downloadDocument('cust_12345', 'doc_pass123', '123', './downloaded_document.pdf');
```

**Java Download Example**

java

```
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DocumentDownloader {
    public static void downloadDocument(String customerId, String documentId, 
                                      String authToken, String outputPath) throws IOException {
        String urlString = String.format(
            "https://stagep.tst-apidmndelss.com/v2/customer/%s/file/%s",
            customerId, documentId
        );
        
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", authToken);
        
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String contentType = connection.getContentType();
            String contentDisposition = connection.getHeaderField("Content-Disposition");
            
            try (InputStream inputStream = connection.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(outputPath)) {
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
            
            System.out.println("Document downloaded successfully");
            System.out.println("Content-Type: " + contentType);
            System.out.println("Content-Length: " + connection.getContentLength());
        } else {
            System.err.println("Error downloading document: " + responseCode);
        }
    }
    
    // Usage
    public static void main(String[] args) {
        try {
            downloadDocument("cust_12345", "doc_pass123", "123", "downloaded_document.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

#### **Common Download Scenarios**

**1. PDF Document Download**

**Request:**

bash

```
curl -X GET 'https://stagep.tst-apidmndelss.com/v2/customer/cust_12345/file/doc_bank123' \
  -H 'Authorization: 123' \
  -o bank_statement.pdf
```

**Expected Response:**

* Content-Type: `application/pdf`
* File: PDF binary data

**2. Image Document Download**

**Request:**

bash

```
curl -X GET 'https://stagep.tst-apidmndelss.com/v2/customer/cust_12345/file/doc_id456' \
  -H 'Authorization: 123' \
  -o drivers_license.jpg
```

**Expected Response:**

* Content-Type: `image/jpeg` or `image/png`
* File: Image binary data

**3. Direct Browser Display**

**HTML Example:**

html

```
<a href="https://stagep.tst-apidmndelss.com/v2/customer/cust_12345/file/doc_pass123" 
   target="_blank"
   onclick="event.preventDefault(); window.open(this.href, '_blank');">
   View Passport Document
</a>
```

**4. Inline Display in Application**

**JavaScript Example:**

javascript

```
async function displayDocument(customerId, documentId, authToken) {
    const response = await fetch(
        `https://stagep.tst-apidmndelss.com/v2/customer/${customerId}/file/${documentId}`,
        {
            headers: { 'Authorization': authToken }
        }
    );
    
    if (response.ok) {
        const blob = await response.blob();
        const url = URL.createObjectURL(blob);
        
        // For PDFs
        if (response.headers.get('Content-Type') === 'application/pdf') {
            window.open(url, '_blank');
        }
        // For images
        else if (response.headers.get('Content-Type').startsWith('image/')) {
            const img = document.createElement('img');
            img.src = url;
            document.body.appendChild(img);
        }
    }
}
```

***

### **Error Responses**

1. **Document Not Found**:

   text

   ```
   HTTP/1.1 404 Not Found
   Content-Type: application/json

   { "error": "Document not found: doc_99999" }
   ```
2. **Customer Not Found**:

   text

   ```
   HTTP/1.1 404 Not Found
   Content-Type: application/json

   { "error": "Customer not found: cust_99999" }
   ```
3. **Unauthorized**:

   text

   ```
   HTTP/1.1 401 Unauthorized
   Content-Type: application/json

   { "error": "Unauthorized" }
   ```
4. **Access Denied**:

   text

   ```
   HTTP/1.1 403 Forbidden
   Content-Type: application/json

   { "error": "Access denied to document" }
   ```

***

### **Notes**

* **Binary Response**: This endpoint returns raw binary data, not JSON
* **File Size**: Large files are streamed efficiently
* **Security**: Documents are accessed with proper authentication and authorization checks
* **Caching**: Responses include cache headers for performance optimization
* **Bandwidth**: Consider file sizes when downloading multiple documents

**Best Practices**:

* Always check response status code before processing binary data
* Use appropriate Accept headers when expecting specific file types
* Handle large files with streaming to avoid memory issues
* Verify file integrity after download using Content-Length header
* Implement proper error handling for network failures

**Supported File Types**:

* **PDF**: `application/pdf`
* **Images**: `image/jpeg`, `image/png`, `image/gif`
* **Documents**: `application/msword`, `application/vnd.openxmlformats-officedocument.wordprocessingml.document`
* **Text**: `text/plain`

**Download Limits**:

* Maximum file size: 50MB
* Rate limiting: 100 downloads per hour per user
* Concurrent downloads: 5 simultaneous downloads per user


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.delos.financial/documents/download-document.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
