Let's understand the microservice scenario where we are going to deploy a serverless hello world function that will respond to HTTP events through the API Gateway.
The Amazon API Gateway service enables you to create, manage, and publish a RESTful API to interact with AWS resources at any scale. The API Gateway provides an interface where you expose the backend through the REST application programming interface.
To enable the AWS serverless infrastructure, the API Gateway plays an important role, as it can be configured to execute the Lambda functions.
Now, we are going to configure an API Gateway service to executes the Lambda function
Here is the hello world function:
When we integrate the AWS Lambda function with the API Gateway, the Lambda function must return a dictionary object with the required keys as statusCode, headers, and body. The value of the body attribute must be in a JSON string. Hence, we converted the Python dictionary into a JSON string.
It's time to integrate the API Gateway with the Lambda function. As we have seen in our previous discussion about triggers, we are going to add a trigger with the API Gateway:
We are going to create an API Gateway service with the name as LambdaMicroservice. The API Gateway enables you to create and maintain a deployment stage as per your requirement.
If you want to secure your API then you have two options—using AWS IAM and opening it with the access key, or keeping it as open, making it publicly available.
AWS IAM (Identity Access Management) is an AWS cloud service that is helpful in creating a secure access credential in order to access AWS cloud services.
Opening with the access key feature allows you to generate the key from the API Gateway console. In our case, we are going to keep the security open only, as we need to access our API publicly:
Once you add and save the changes, the REST API is ready within a few seconds. The invoke URL is our REST API endpoint.
Let's hit the invoke URL using the curl command-line tool and see what happens:
$ curl https://cfi6872cxa.execute-api.us-east-2.amazonaws.com/prod/HelloWorld
{"message": "Hello World returned in JSON"}
That's it. We are done with creating a serverless RESTful API using AWS Lambda and the API Gateway. Now, we are going to see how we can interact with the AWS services using the AWS CLI.