> For the complete documentation index, see [llms.txt](https://docs.os.uk/os-apis/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.os.uk/os-apis/accessing-os-apis/os-downloads-api/getting-started/automating-os-premium-data-downloads.md).

# Automating OS Premium data downloads

This guide takes you though the process of automating the download of OS Premium data downloads.

## What you need

* A basic understanding of automatic processing of JSON data and basic procedural (if-then-else) programming
* OS Downloads API added to an API project in the OS Data Hub with an API Key, see [Getting started with an API project](/os-apis/core-concepts/getting-started-with-an-api-project.md) for more information
* A text editor like Visual Studio Code
* A working installation of [Node.js](https://nodejs.org/) and the popular [axios](https://github.com/axios/axios) module

{% hint style="info" %}
Please read the [download support documentation](https://osdatahub.os.uk/support/faqs/downloads) before working with data packages.
{% endhint %}

{% stepper %}
{% step %}

#### Get a list of data packages

Get the list of products available from [Technical specification](/os-apis/accessing-os-apis/os-downloads-api/technical-specification.md#datapackages) endpoint including the product `id` and `version`.

```javascript
const axios = require('axios');
const apiKey = 'Insert API key here';

async function getList() {
    const dataPackageList = await axios({
        url: 'https://api.os.uk/downloads/v1/dataPackages',
        headers: {
            key: apiKey
        }
    });
    /* For explanation and debugging purposes we display the full response from the API in the console */
    console.log(dataPackageList.data);
    for (const dataPackage of dataPackageList.data) {
        /* This will print out the url of the data package id which can be used in another request. This would be the
           ideal place to call another function which continues the processing or filters down the results to the set required. */
        console.log(dataPackage.url);
    }
}
getList();
```

{% hint style="warning" %}
This is similar to a [manual download](https://osdatahub.os.uk/data/downloads/open) in that you first need to discover what is available. Be mindful that list items can change.
{% endhint %}

Each entry in the JSON response provides data package metadata, as well as information about available versions of the data package.

* You may at this point wish to create a loop that iterates through all available data packages or a subset that you are interested in based on common attributes (for example, vector data in a certain format).
* You could store the data package `id` and `version ids`. That way you can easily check periodically for new versions of the data package being available, simply by comparing the versions we provide with the ones that you hold.
  {% endstep %}

{% step %}

#### Get product specific information

While the key parts of this are already provided in step 1, this shows another way of getting to specific detail.

```javascript
const axios = require('axios');

/* This function will return information about a specific data package.
   You will need to insert both a dataPackageId and API key to complete the implementation. */
const apiKey = 'Insert API key here';
const dataPackageId = 'Insert data package id here';

async function getDataPackageDetails() {
    const dataPackageDetails = await axios({
        url: 'https://api.os.uk/downloads/v1/dataPackages/' + dataPackageId,
        headers: {
            key: apiKey
        }
    });
    console.log(dataPackageDetails.data);
    /* At this point we could insert another function to process the results or act on them/download them */
}
getDataPackageDetails();
```

{% endstep %}

{% step %}

#### Download data

Using the product `id` from the previous response make a call to the [Technical specification](/os-apis/accessing-os-apis/os-downloads-api/technical-specification.md#datapackages-datapackageid-versions-versionid)endpoint. Once you obtain the download links for the data package version you are ready to download the data.

{% hint style="info" %}
By including `latest` as the `versionId` this will return information about the most recent data package version, including a list of the files that are available to download.
{% endhint %}

In this example, we hard code the data package id that we are interested in. This can also be provided dynamically into the function, allowing the same function to be used for multiple products and formats.

```javascript
const fs = require('fs');
const axios = require('axios');

const apiKey = 'Insert API key here';
const dataPackageId = 'Insert data package id here';

/* ============================================================
Function: Uses Axios to download file as stream using Promise
============================================================ */
const download_file = (url, fileName) =>
    axios({
        url,
        headers: {
            key: apiKey
        },
        responseType: 'stream'
    }).then(
        response =>
            new Promise((resolve, reject) => {
                response.data
                    .pipe(fs.createWriteStream(fileName))
                    .on('finish', () => resolve())
                    .on('error', e => reject(e));
            }
    )
);

/* ============================================================
Download all of the files in the latest data package version
============================================================ */
async function downloadFiles() {
    try {
        const downloadInfo = await axios({
            url: 'https://api.os.uk/downloads/v1/dataPackages/' + dataPackageId + '/versions/latest',
            headers: {
                key: apiKey
            }
        });
        for (const download of downloadInfo.data.downloads) {
            let downloadFile = await download_file(download.url, download.fileName);
            console.log(`Downloaded file ${download.fileName}`);
        }
        console.log('Completed downloading files');
    } catch (error) {
        console.error(error);
    }
}

downloadFiles();
```

{% endstep %}
{% endstepper %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.os.uk/os-apis/accessing-os-apis/os-downloads-api/getting-started/automating-os-premium-data-downloads.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
