Cook a recipe with AWS: A simple API using API-Gateway
Tags: webdev, microservices, programming, testing
Published: 2022-12-22 21:46:10


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vcel4i71gvumiznxpu2d.png)





## 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
- Lambda Function (ReverseString) Recipe: [Cook a recipe with AWS: Simple and Easy Lambda Functions](https://dev.to/aws-builders/cook-a-recipe-with-aws-simple-and-easy-lambda-functions-3e98)

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


**Lets Jump to the Recipe**

## <u>Build an API using API Gateway to trigger Lambda Function</u>

<u>Steps to create</u>

- Open the **API-Gateway** from aws console


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fgc89uvu4xj2a3r1eix9.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7lxue7ef4p5l4n14mkv.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zcguyg3ftkmo4uzzy432.png)

- 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


<u>REST API endpoint types</u>

> - **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nf12tlzfqszg43263oh.png)

Now, Lets add some Resources

- Click **Actions** and Select **Create Resource**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkl8jfkitd92mbozvjhy.png)

> **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twrjxwon9uz4mnpx2gez.png)


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/umn8v24vymkskghat4a1.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtnsbagbpu5lzisq81e4.png)

- Go to **Actions** and Click **Create Method**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dsf6cvdvzxquvd6m20f9.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jzxk91cfs5qp18qcffu.png)

- Click **Tick icon** to **save**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z1ja5qx2pasq9denz7om.png)

 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hukdkgewg1kv9921w9qt.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bqwc2zn5l9wyn8qydk5z.png)

Now its time to test the function manually 


**<u>Test the API </u>**

- Click the  lightning bolt that says **Test**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7n4u8h5e17w4vhdo6ok.png)

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

`{
"first_name": "cloud"
}`


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g26lxy17o7jivt6gdnkf.png)

- Click the **Test** button

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6pzzhfxohjtyi127ddvz.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f797we5swnnrfuq6xtuv.png)
 
The **HTTP 200 OK** **success status response code** indicates that the request has succeeded.



Now its time to deploy the API 

**<u>Deploy the API </u>**

- Select **Deploy API** from the **Actions** drop-down:



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pz8dvly5r2t5ihsdto9h.png)


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




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brafr4r9ev3dmlljz51l.png)

- You can see the newly created stage as well as **invoke url**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2v09447kj9mje7d1tdiq.png)

> **<u>Invoke URL</u>**
> 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4x3k49xxornfk1ieuaxi.png)
> 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.

## <u>Create a Canary using Amazon CloudWatch Synthetics to Monitor API </u>

> **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hhp87a5jmx6oy0ot3co1.png)

- Click on **Synthetics Canaries** link which is displayed below **Application Monitoring**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sag3gr8tmfqr6g4psguj.png)

> **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ys0p36hv8kh9kqfdoupg.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yzutf9v6ekonw5w0zwyn.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/laa28nfzo6kdzjjvpdrp.png)


- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39i8p2rshj67tlqzzt48.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cev29yfa852r3zytltcc.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p4nnhqa1410vq2td1qr8.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/czhb556mt9wjc7j2n345.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jydy2pm1tzedkzkqmm2.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibeatf3l075tjo968xkx.png)

- **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4m6kj0frqtpkzc113lcv.png)

- **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mu5imjcvww5lvieyw9ez.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evsgu2grb4izrqivrlad.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/81rcl71l0q7oyqqwcy2a.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b32b4rwvkaxdqrrue4l2.png)

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


<u>Note</u>: 
- **Delete the resources(Lambda function, API, Canary) after use**
- **Canary** should be **stopped** to enable **Delete** option