Automating OS OpenData downloads
What you need
1
const axios = require('axios');
async function getList() {
const productList = await axios('https://api.os.uk/downloads/v1/products');
/* For explanation and debugging purposes we display the full response from the API in the console */
console.log(productList.data)
for (const product of productList.data) {
/* This will print out the product 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(product.id)
}
}
getList() 2
const axios = require('axios');
/* This function will return the specific information on OS Open Greenspace */
async function getProductDetails() {
const greenspaceDetails = await axios('https://api.os.uk/downloads/v1/products/OpenGreenspace');
console.log(greenspaceDetails.data)
/* At this point we could insert another function to process the results or act on them/download them */
}
getProductDetails()3
const fs = require('fs');
const axios = require('axios');
/* ============================================================
Function: Uses Axios to download file as stream using Promise
============================================================ */
const download_file = (url, filename) =>
axios({
url,
responseType: 'stream'
}).then(
response =>
new Promise((resolve, reject) => {
response.data
.pipe(fs.createWriteStream(filename))
.on('finish', () => resolve())
.on('error', e => reject(e));
}
)
);
/* ============================================================
Download Files in Order
============================================================ */
async function downloadFiles() {
try {
const downloadInfo = await axios.get('https://api.os.uk/downloads/v1/products/OpenGreenspace/downloads')
for (const download of downloadInfo.data) {
if(download.area !== 'GB' && download.format === 'ESRI® Shapefile') {
let downloadFile = await download_file(download.url, `${download.area}.zip`);
console.log(`Downloaded file ${download.area}`)
}
}
console.log('Completed downloading files')
} catch (error) {
console.error(error);
}
}
downloadFiles()Last updated
Was this helpful?