We can create a REST API using AWS API Gateway and AWS Lambda by Proxy integration.
For Proxy integration, when API Gateway receives the request, it sends proxy resources such as path information and request body to Lambda function. Lambda function generates a responses based on information sent by API gateway. This response is sent back to API Gateway which send this response back to API user. In Lambda function, you can call other aws services such as store data in s3 bucket and send message to sqs before send back the response.
Step 1: Create a AWS Lamda function
Use Python as example. After create function, need to edit lambda_hander
import json
def lambda_handler(event, context):
# event has info of request passed by API Gateway
userId = event['queryStringParameters']['userId']
# build response body
body = {"user_id": userId, "message": "processed by Lambda"}
# build response
response = {'statusCode': 200, 'headers': {}}
# let API caller know that our body is in json format
response['headers']['content-type'] = 'application/json'
response['body'] = json.dumps(body)
return response
Note for node.js. In node.js, you can do
exports.myhandler = {event, context, callback) => {
//get path parameters
event.pathParamters...
//get body
event.body
//get query string
event.queryStringParameters ...
}
Note for debug:
For Python, use print something
For node.js, console.log something
Then we can see these debug info in cloudwatch
Step 2: Create a API Gateway
1. Pick Rest type
2. Create resource. Give it a name
3. Create method. We choose GET for this example.
4. In Get set up. Choose Integration type: Lambda Function. Also check "Use Lambda Proxy integration". Link the lambda function just created.
Step 3: deplay this API Gateway
Step 4: try it
find the api url and append a user id such as ?user_id=1
Step 5: add custom domain
You may want to add custom domain for this api.
Here is a good youtube video about setting up custom domain for API gateway
Here is a good youtube video about Gateway API and lamda function.
No comments:
Post a Comment