Mangesh Tak
Mangesh Tak

Reputation: 396

Unable to perform getobject from aws s3 in aws-lambda

I am new to aws-lambda and aws-s3. I am trying to create one microservice using api-gateway, aws s3 and aws lambda. I have written lambda function to retrive object from s3, but it sends null and not throwing any error. I am not sure what is going wrong. I have setup role and gave access to s3 and used that role for lambda

const AWS = require('aws-sdk'); 
var s3 = new AWS.S3();
exports.handler = async (event) => {
    var params = {
      "Bucket": "bucketname",
      "Key": "keyname"
        };

    s3.getObject(params, function(err, data){
      if(err) {
          return "error while fetching data";
      } else {
          return data;
      }

    });
};

What am I doing wrong here?

Upvotes: 0

Views: 421

Answers (1)

Deiv
Deiv

Reputation: 3097

You should return the data in the proper response format required for API gateway proxy and use the callback parameter to reply, so change your function to look like this:

const AWS = require('aws-sdk'); 
var s3 = new AWS.S3();

exports.handler = async (event, context, callback) => {
    var params = {
        "Bucket": "bucketname",
        "Key": "keyname"
    };

    s3.getObject(params, function(err, data){
        if(err) {
            return callback(new Error("error while fetching data"));
        } else {
            let response = {
                statusCode: 200,
                headers: {
                    "x-custom-header" : "my custom header value"
                },
                body: JSON.stringify(data)
            };
            return callback(null, response);
        }
    });
};

If you're not using API gateway proxy Lambda integration, then you can simply change the response to just return callback(null, data);

Upvotes: 1

Related Questions