API Databank – Redirects and CORS restrictions
The File Download and Queue Download endpoints employ a redirect response to indicate successful completion and to pass along the newly generated download URL. Any client-side API call must expose this redirect URL (i.e. the download URL). However, in many web browsers this is will not be possible because of CORS restrictions. Therefore, setting up an intermediary application is necessary to make these calls and forward along the redirect URL. In our example code, we have included a simple Webtask script (js/file-download.js) to indicate one way this can be done.
Webtasks are one method for launching simple, lightweight web applications like this, so your code can run remotely without the need to configure server hardware or software. This particular framework uses Javascript and a wide range of NPM modules. More on Webtasks at https://webtask.io/.
var request = require(‘request@2.67.0’)
API_URL = ‘https://services.oxfordeconomics.com’;
// this function takes a saved selection id and makes a GET
// request to the filedownload endpoint, forwarding the download
// url, which appears as the redirect location in the response headers
// from the api
//
// note: request headers and body are accessible via the context
// object e.g. context.data.*, context.headers.* and the response
// data is simply handed off to the callback function. in this
// case we’re returning the redirect url as plain text
module.exports = function (context, callback)
{
var api_url = API_URL + ‘/api/filedownload’;
var api_key = context.data.api_key;
var api_resource_id = context.data.api_resource_id || “”;
if (!api_resource_id || !api_key)
{
callback(400, null);
}
else
{
api_resource_id = “/” + api_resource_id;
var options =
{
method: ‘GET’,
followRedirect: false,
uri: api_url + api_resource_id,
headers:
{
‘Api-Key’: api_key
}
};
request(options, function(error, response, body)
{
if (response.statusCode >= 300 && response.statusCode < 400)
{
callback(null, response.headers.location);
}
else
{
callback(response.statusCode, error);
}
});
}