Geole
Geole

Reputation: 376

Invoking Rest API from Lambda (JS; Web Console)

_

MY CHALLENGE:

I would like to access a third party Rest API from within my Lambda function. (e.g."http://www.mocky.io/v2/5c62a4523000004a00019907").

This will provide back a JSON file which I will then use for data extraction

_

MY CURRENT CODE:

var http = require('http');

exports.handler = function(event, context, callback) {
    console.log('start request to Mocky');

    http.get('http://www.mocky.io/v2/5c62a4523000004a00019907', function(res) {
            console.log(res);

        })
        .on('error', function(e) {

            console.log("Got error: " + e.message);
        });
};

This does not throw an error but also does not seem to provide back the JSON

_

MY OPEN QUESTIONS:

1) How can I extract the JSON so that I can work on it

2) I will probably need to also send through an Authentification in the request header (Bearer) in the future. Will this also be possible with this method?

Upvotes: 0

Views: 831

Answers (2)

Matt Morgan
Matt Morgan

Reputation: 5303

The problem is likely that your lambda function is exiting before logging the response.

We use Authorization headers all the time to call our lambdas. The issue of if you can use one to call the third party API is up to them, not you, so check the documentation.

Since your HTTP call is executed asynchronously, the execution of the lambda continues while that call is being resolved. Since there are no more commands in the lambda, it exits before your response returns and can be logged.

EDIT: the http.get module is difficult to use cleanly with async/await. I usually use superagent, axios, or request for that reason, or even node-fetch. I'll use request in my answer. If you must use the native module, then see EG this answer. Otherwise, npm install request request-promise and use my answer below.

The scheme that many people use these days for this kind of call uses async/await, for example (Requires Node 8+):

var request = require('request-promise')

exports.handler = async function(event, context, callback) {
    console.log('start request to Mocky');
    try {
        const res = await request.get('http://www.mocky.io/v2/5c62a4523000004a00019907')
        console.log(res)
        callback(null, { statusCode: 200, body: JSON.stringify(res) })
    }
    catch(err) {
        console.error(err.message)
        callback('Got error ' + err.message)
    }
};

The async/await version is much easier to follow IMO.

Everything inside an async function that is marked with await with be resolved before the execution continues. There are lots of articles about this around, try this one.

Upvotes: 1

Ore
Ore

Reputation: 1032

There are a lot of guys having an equal problem already solved... Look at that or that

Upvotes: 0

Related Questions