> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pdf.co/llms.txt
> Use this file to discover all available pages before exploring further.

# File Download

> This endpoint allows you to retrieve files stored in [PDF.co Files Storage](https://app.pdf.co/files) using a unique filetoken. Access is restricted so that only the account owning the file with the correct filetoken can retrieve it.

## `GET /v1/file/download/{filetoken}`

**Endpoint URL Format:**

```
https://api.pdf.co/v1/file/download/{filetoken}
```

Replace `{filetoken}` with the actual filetoken identifier. For example:

```
https://api.pdf.co/v1/file/download/a1d30e75adf5eaa.................
```

**Key Features:**

* **Exclusive Access:** The endpoint strictly controls access, allowing only the account owner with the correct filetoken to retrieve the associated file.
* **Secure File Retrieval:** Files are securely stored and can only be accessed through the authenticated API endpoint using the filetoken.
* **File Token Based:** Uses a unique filetoken identifier to access files stored in PDF.co's built-in file storage.

<Note>Files must be uploaded to PDF.co's built-in file storage at [https://app.pdf.co/files](https://app.pdf.co/files) to obtain a filetoken. The filetoken is used to securely reference and retrieve files through the API.</Note>

## Request Headers

| Header      | Type   | Required | Description                                                                                                  |
| ----------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------ |
| `x-api-key` | string | *Yes*    | Your API key for authentication. Get your API key by registering at [https://app.pdf.co](https://app.pdf.co) |

## Response

The endpoint returns the file content directly with the appropriate Content-Type header based on the file type. The response is a binary file stream.

### Response Headers

| Header                | Type    | Description                                                      |
| --------------------- | ------- | ---------------------------------------------------------------- |
| `Content-Type`        | string  | The MIME type of the file (e.g., `application/pdf`, `image/png`) |
| `Content-Disposition` | string  | The filename and disposition information                         |
| `Content-Length`      | integer | The size of the file in bytes                                    |

### Error Responses

If an error occurs, the endpoint returns a JSON response with the following structure:

| Parameter   | Type    | Description                                                                                                                       |
| ----------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `error`     | boolean | Indicates whether an error occurred (`true` means error)                                                                          |
| `status`    | integer | Status code of the request (200, 404, 403, 500, etc.). For more information, see [Response Codes](/api-reference/response-codes). |
| `message`   | string  | Error message describing what went wrong                                                                                          |
| `errorCode` | integer | Error code of the request (400, 401, 403, 404, 500, etc.)                                                                         |

## `Example` Response (Success)

<Note>On successful request, the endpoint returns the file binary content directly. The following example shows the response headers for a PDF file:</Note>

**Response Headers:**

```
Content-Type: application/pdf
Content-Disposition: attachment; filename="document.pdf"
Content-Length: 245678
```

## `Example` Error Response

<Note>To see the main response codes, please refer to the [Response Codes](/api-reference/response-codes) page.</Note>

```json theme={null}
{
    "status": "error",
    "errorCode": 404,
    "error": true,
    "message": "record not found. IMPORTANT: If you need to set JSON data then convert it into string first (e.g. using JSON.stringify(obj) ). Check https://docs.pdf.co for more details."
}
```

<Note>
  **Inconsistent URL Encoding in cURL Output:** When using cURL to make API requests, the output JSON may show URL characters encoded as Unicode escape sequences. For example, the ampersand character (`&`) may appear as `\u0026` in the cURL output. This is normal JSON encoding behavior and does not affect the validity of the URL. The URL will function correctly when used, as JSON parsers automatically decode these escape sequences. If you're parsing the response programmatically, your JSON parser will handle this conversion automatically.
</Note>

## Code Samples

<Tabs>
  <Tab title="CURL">
    ```bash theme={null}
    curl --location --request GET 'https://api.pdf.co/v1/file/download/YOUR_FILETOKEN_HERE' \
    --header 'x-api-key: *******************' \
    --output downloaded-file.pdf
    ```
  </Tab>

  <Tab title="JavaScript/Node.js">
    ```javascript theme={null}
    var https = require("https");
    var fs = require("fs");

    const API_KEY = "*************************************";
    const FILETOKEN = "YOUR_FILETOKEN_HERE";

    function downloadFile(apiKey, filetoken) {
      return new Promise((resolve, reject) => {
        // Prepare request to `file/download` API endpoint
        let reqOptions = {
          host: "api.pdf.co",
          path: `/v1/file/download/${filetoken}`,
          headers: { "x-api-key": apiKey }
        };
        
        // Send request
        https.get(reqOptions, (response) => {
          if (response.statusCode === 200) {
            // Create write stream for downloaded file
            const fileStream = fs.createWriteStream("downloaded-file.pdf");
            response.pipe(fileStream);
            
            fileStream.on("finish", () => {
              fileStream.close();
              console.log("File downloaded successfully");
              resolve();
            });
          } else {
            // Handle error response
            let data = "";
            response.on("data", (chunk) => {
              data += chunk;
            });
            response.on("end", () => {
              try {
                const errorData = JSON.parse(data);
                console.log("Error: " + errorData.message);
                reject(errorData);
              } catch (e) {
                console.log("Error: " + response.statusCode);
                reject(new Error(`HTTP ${response.statusCode}`));
              }
            });
          }
        })
        .on("error", (e) => {
          // Request error
          console.log("error: " + e);
          reject(e);
        });
      });
    }

    downloadFile(API_KEY, FILETOKEN);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests
    import os

    # The authentication key (API Key).
    # Get your own by registering at https://app.pdf.co
    API_KEY = "*************************************"

    # Base URL for PDF.co Web API requests
    BASE_URL = "https://api.pdf.co/v1"

    # File token from PDF.co file storage
    FILETOKEN = "YOUR_FILETOKEN_HERE"

    # Destination file path
    DESTINATION_FILE = "downloaded-file.pdf"

    # Prepare URL for file download
    url = f"{BASE_URL}/file/download/{FILETOKEN}"

    # Execute request
    response = requests.get(url, headers={"x-api-key": API_KEY}, stream=True)

    if response.status_code == 200:
        # Save file to disk
        with open(DESTINATION_FILE, "wb") as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)
        print(f"File downloaded successfully as '{DESTINATION_FILE}'")
    else:
        # Handle error response
        try:
            error_data = response.json()
            print(f"Error: {error_data.get('message', 'Unknown error')}")
        except:
            print(f"Error: HTTP {response.status_code}")
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php
      $apiKey = "***************";
      $filetoken = "YOUR_FILETOKEN_HERE";
      $destinationFile = "downloaded-file.pdf";
      
      $url = "https://api.pdf.co/v1/file/download/" . $filetoken;
      
      // Create request
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey));
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
      
      // Open file for writing
      $fileHandle = fopen($destinationFile, "w");
      curl_setopt($curl, CURLOPT_FILE, $fileHandle);
      
      // Execute request
      curl_exec($curl);
      $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
      
      fclose($fileHandle);
      curl_close($curl);
      
      if ($httpCode == 200) {
        echo "File downloaded successfully as '$destinationFile'";
      } else {
        echo "Error: HTTP $httpCode";
      }
    ?>
    ```
  </Tab>

  <Tab title="C#">
    ```csharp theme={null}
    using System;
    using System.Net;
    using System.IO;

    namespace PDFcoApiExample
    {
        class Program
        {
            // The authentication key (API Key).
            // Get your own by registering at https://app.pdf.co
            const String API_KEY = "***********************************";
            
            const string FILETOKEN = "YOUR_FILETOKEN_HERE";
            const string DESTINATION_FILE = "downloaded-file.pdf";
            
            static void Main(string[] args)
            {
                // Create standard .NET web client instance
                WebClient webClient = new WebClient();
                
                // Set API Key
                webClient.Headers.Add("x-api-key", API_KEY);
                
                // Prepare URL for file download
                string url = $"https://api.pdf.co/v1/file/download/{FILETOKEN}";
                
                try
                {
                    // Download file
                    webClient.DownloadFile(url, DESTINATION_FILE);
                    
                    Console.WriteLine($"File downloaded successfully as '{DESTINATION_FILE}'");
                }
                catch (WebException e)
                {
                    Console.WriteLine($"Error: {e.Message}");
                }
                finally
                {
                    webClient.Dispose();
                }
                
                Console.WriteLine();
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            }
        }
    }
    ```
  </Tab>
</Tabs>
