POST JSON object to aws lambda

前端 未结 2 625
我寻月下人不归
我寻月下人不归 2021-02-15 04:11

How can I post a json object to aws lambda function through aws API gateway ?

p.s.- My goal is to write the lambda function in python and then post it to aws SQS.

<
2条回答
  •  天涯浪人
    2021-02-15 04:55

    I figured it out. Now I have a API Gateway acceptiong client posted JSON data of a specified format and then passing it to a AWS-Lambda function which, dumps the data into a AWS-SQS. The steps are explained below in details-

    STEP 1-

    Create a lambda function in any supported languages (I have used Python 3.6). Here is a sample code.

    import boto3  
    import json
    
    def lambda_handler(event, context):
    
        sqs = boto3.resource('sqs')
    
        queue = sqs.get_queue_by_name(QueueName='userData')
    
        response = queue.send_message(MessageBody=json.dumps(event))
    
        return {
                    "status":"0",
                    "message":"",
                    "pubId":event["ClientID"],
                    "routetitle":event["routeTitle"]
                }
    

    Note: I have imported both json and boto3 library which are available in aws context no need to add any more file. Also see that I have not specified any details for SQS other than the name because both of my Lambda function and SQS are in same AWS region. I am dumping the whole "event" variable to SQS as this only contains the posted JSON data.

    STEP 2-

    Now in the AWS console goto "API Gateway" and then create a new API Gateway and then create a "POST" action under resources.

    Please check the screenshot

    Now, under the post action, click on "Integration request". Now add a body template to it like the example given below-

    {
      "userMobile" : "$input.params('userMobile')",
      "ClientID" : "$input.params('ClientID')",
      "routeTitle" : "$input.params('routeTitle')"
    }
    

    Also, make sure that you have the "Integration Type" of your API as "Lambda" and the Lambda function we created in STEP-1 is connected to the API.

    Now, we are almost done. now all we have to do is create a stage for the API that we have created and deploy the API. ***

    Please note the HTTP URL of the API after deployment.

    STEP 3-

    Now go to the "Simple Queuing Service (SQS)" and then create a simple SQS with keeping all the default parameters. Make sure the queue name is matching with the one you have provided in your Lambda function and both your Lambda function and your SQS are in same AWS region.

    Now, you can POST JSON data in the same format to your API and your Lambda function will dump it to the SQS queue, where you can go and view the data.

    You can also test the API using tools like Fidler.

    *** make sure to redeploy the API for every time you make a change to it.

提交回复
热议问题