DEV Community

Cover image for Cook a recipe with AWS: A simple API using API-Gateway
Nandini Rajaram for AWS Community Builders

Posted on • Updated on

Cook a recipe with AWS: A simple API using API-Gateway

Image description

Application Programming Interface

Application Programming Interface (API) are tools that make it possible for two software components to communicate with one another, Applications can access data, business logic, or functionality from backend services through APIs, which serve as the application's front door.

API Gateway : The front door to access API

API Gateway is a service that facilitates the creation, publishing, maintenance, monitoring, and security of your APIs at any scale.

API Gateway will facilitate management of your APIs

API types supported by Amazon API Gateway

  • REST API REST stands for representational state transfer, defines a set of functions such as GET, PUT, and DELETE that clients can use to access server data. The main feature of a REST is statelessness(The lack of state) means that servers do not store client information between requests.

REST API in API Gateway is a collection of resources and methods that are integrated with backend HTTP endpoints, Lambda functions, or other AWS services. API Gateway REST APIs use a request-response model, where a client sends a request to a service and the service responds back synchronously. This kind of model is suitable for many different kinds of applications that depend on synchronous communication.

  • HTTP API With Hypertext Transfer Protocol (HTTP) APIs, you can create RESTful APIs with lower latency and lower cost than REST APIs. You can use HTTP APIs to send requests to Lambda functions or to any routable HTTP endpoint.
  • WebSocket API WebSocket API maintain a persistent connection between connected clients to facilitate real-time message communication and are often used in real-time applications such as chat applications, collaboration platforms, multiplayer games, and financial trading platforms. They support bidirectional communication that lets clients and services independently send messages to each other

Now, We are going to cook a REST API endpoint using API gateway which triggers the Lambda Function ReverseString

Ingredient

Prerequisites

Log into AWS account with a valid user credentials (Root user not preferred)

Lets Jump to the Recipe

Build an API using API Gateway to trigger Lambda Function

Steps to create

  • Open the API-Gateway from aws console

Image description

  • Now We are going to create a REST API to trigger the lambda function. Scroll down a little and You can see REST API option. Click the Build button at the bottom right of it

Image description

  • Now, If you are creating the API for the first time, You should be able to see this alert box. Click OK button to accept the alert

Image description

  • Now Choose the REST protocol under the Choose the protocol section

  • Choose New API under create new API section (Example API would be selected by default)

  • In settings section, Specify a name to the API, I am going to give ReverseStringTriggerAPI

  • Give a Description though its an optional field, Its a good practice to specify here what this API is expected to do. I am going to add the following text to the description field
    "An api to trigger the lambda function ReverseString"

  • You must choose the appropriate endpoint type for the traffic and usage patterns you anticipate before you begin creating your APIs. By default Regional would be selected as endpoint type. Keep it as it is

REST API endpoint types

  • Regional Endpoint The regional endpoint is designed to reduce latency when calls are made from the same AWS Region as the API. Here, API Gateway does not deploy its own CloudFront distribution in front of your API. Instead, traffic destined for your API will be directed straight at the API endpoint in the Region where you’ve deployed it.
  • Edge-optimized endpoint The edge-optimized endpoint is designed to help you reduce client latency from anywhere on the internet. Here the api gateway automatically configure a fully managed CloudFront distribution to provide lower latency access to your API. This endpoint-type configuration lowers the API's first hit latency. Using a managed CloudFront distribution also saves you from having to manage or pay for a CDN separately from API Gateway.
  • Private endpoint As the name indicates, The private endpoint is designed to expose APIs only inside your selected Amazon Virtual Private Cloud (Amazon VPC). Here requests are only routable and can only originate from within a single virtual private cloud (VPC) that you control. This endpoint type is ideal for applications that have very secure workloads, such as healthcare or financial data that cannot be exposed publicly on the internet.
  • Now click Create API button to create the API

Image description

Now, Lets add some Resources

  • Click Actions and Select Create Resource

Image description

Create Resource option is used to create a new resource. When you do this, you are creating addressable resources as a tree of API resource entities, with the root resource at the top of the hierarchy. The root resource is relative to the API's base URL.

  • Now, Name the resource as "reversestringcall"
  • And click Create Resource button

Image description

  • Now, You should be able to see the Resource created in tree format as shown below

Image description

Once you have created the resource, you can associate methods with your resources.

Lets add some methods to the resource

  • Click on the Resource link

Image description

  • Go to Actions and Click Create Method

Image description

Now, You will be prompted to choose one of the HTTP verbs such as GET, POST, or OPTIONS.

  • Choose POST method

POST is an HTTP method designed to send data to the server from an HTTP client. The HTTP POST method requests the web server accept the data enclosed in the body of the POST message

Image description

  • Click Tick icon to save

Image description

Now Lets configure the Integration

  • In the Setup step, select Lambda Function as the Integration type
  • Select the region where Lambda function is deployed
  • Choose the Lambda function which needs to be triggered

Note: In this example, I am creating the API on the same region where my Lambda function is deployed that is us-west-1

Image description

  • Click Save, and then Click OK to give permission to the API Gateway to run your Lambda function.

Image description

Now its time to test the function manually

Test the API

  • Click the lightning bolt that says Test

Image description

  • Scroll down to the Request Body input and add the same JSON code we used with the Lambda function:

{
"first_name": "cloud"
}

Image description

  • Click the Test button

Image description

  • The API is executed and it triggers lambda function with the input on the Request body and Finally the result is generated as shown below

Image description

The HTTP 200 OK success status response code indicates that the request has succeeded.

Now its time to deploy the API

Deploy the API

  • Select Deploy API from the Actions drop-down:

Image description

  • Create a new Deployment stage called v1 by specifying the Stage name and description.
  • Click on Deploy button

Image description

  • You can see the newly created stage as well as invoke url

Image description

Invoke URL
When you deploy your API, you deploy to a stage, a base URL is generated which is also called as the invoke URL
Image description
All APIs created with API Gateway will follow the same pattern as the invoke URL above, with the ID of the API and the Region in which it was created, followed by a stage, and then the resource and resource path you want to expose.

Create a Canary using Amazon CloudWatch Synthetics to Monitor API

Amazon CloudWatch Synthetics
Amazon CloudWatch Synthetics allows you to monitor application endpoints more easily by executing tests on your endpoints every minute, 24x7, and alerts you as soon as your application endpoints don’t behave as expected.

  • Open the CloudWatch from aws console

Image description

  • Click on Synthetics Canaries link which is displayed below Application Monitoring

Image description

Canaries of Amazon CloudWatch Synthetics
Canaries are configurable scripts that run on a schedule, to monitor your endpoints and APIs. They follow the same routes and perform the same actions as a customer, which makes it possible for you to continually verify your customer experience even when you don't have any customer traffic on your applications

  • They monitor your REST APIs, URLs, and website content, and they can check for unauthorized changes from phishing, code injection and cross-site scripting.
  • By using canaries, you can discover issues before your customers do.
  • Click Create Canary button

Image description

  • You can use a blueprint provided by CloudWatch or use your own script by uploading it or importing it from Amazon S3.

  • By default, Use a blueprint option will be selected. We are going to proceed with this

  • On Blueprints section, select API canary

Image description

  • Now, Scroll down and specify a Name to the canary. I am naming it as "reversestringmonitor"

  • Now, tick the checkbox I'm using an Amazon API Gateway API

  • Select the API which we had configured and its stage respectively

Image description

  • You can see that application / endpoint URL getting auto populated based on our selection of the API and its stage

  • Now Lets add a HTTP POST request

Click the Add HTTP request button

Image description

  • Input your HTTP request details. You can add multiple requests to this canary

Image description

  • Add the request data for the post request
  • Tick the checkbox Capture headers and response body to store the headers and response body on S3 bucket

  • Click Save button

Image description

  • Now You will be navigated to the Create Canary page and will be able to see the details about canary configuration

A default script will be generated on Script editor section which would verify that the response status code of the API is 200

Image description

  • You can edit this canary and change run schedule at any time on the schedule section. By default, Run continuously option would be selected

  • Run the canary every 5 minutes is auto selected (You can make the frequency changes as required). Now I am leaving it to default

Image description

  • The canary data retention period can also be configured on Data retention section. For now, I am leaving the default values

Image description

  • Canary run data is stored in an Amazon S3 storage resource bucket. A default S3 bucket will be used or created, You can also select an existing S3 bucket from your AWS account. Now, I am leaving it to default value

Image description

  • We need your permission to put artifacts into S3, and to store logs and publish metrics to Cloudwatch. An IAM role with those permissions will be created by default or You can choose an existing role. Now I am proceeding with the default selection

Image description

  • There are certain optional configurations available such as

    • CloudWatch alarms : You can let Synthetics create alarms for your canary automatically, and customize these later. (No alarms will be configured by default)
    • VPC settings : Use this if your endpoints are under your network (No vpc will be selected by default)
    • Add tags: to canaries to help set permissions, organize, and search for them later (blueprint tag with value _API canary _ will be added by default as per our selections and you can also additional tags as required)
    • Active tracing: For active tracing with AWS X-Ray to help troubleshoot and reduce the mean time to resolution.

AWS X-Ray and Synthetics help you analyze and debug to find the root cause of ongoing failures, identify performance bottlenecks and trends, compare latency rates, and identify if you have enough canary coverage for your APIs and URLs.

Trace my service with AWS X-Ray. checkbox will be enabled by default which will allow you to

  • View canaries in AWS X-Ray and CloudWatch ServiceLens service maps.
  • View traces and segments for each canary run.
  • View trends using AWS X-Ray analytics.

Image description

  • Click Create canary button

You can see a message as below. Please wait for a couple of minutes until the canary is created for you

Image description

  • You will be navigated to Canaries page once the canary is successfully created

  • Wait for a couple of minutes and You can see the API canary which we configured getting executed and test results will be displayed

Image description

  • As per run schedule configuration, The canary will be running every 5 minutes and thus API will be monitored

Note:

  • Delete the resources(Lambda function, API, Canary) after use
  • Canary should be stopped to enable Delete option

Top comments (1)

Collapse
 
vijay_21 profile image
Vijay Ramanathan

Nice recipe