Automating OS Premium data downloads
What you need
1
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();2
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();3
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();Last updated
Was this helpful?