shou2017.com
JP

Trying FetchApi GET with API Gateway

Sun Mar 29, 2020
Sat Aug 10, 2024
AWS

What I want to do

Use the GET method of FetchApi to call API Gateway!

Create API Gateway

From the AWS console, go to API Gateway and create an API.

For Choose API type, select REST API and build it.

For Choose protocol, do as follows:

  • REST
  • New API
  • API name: Hello Amazon API Gateway

Create API Gateway

From Actions, select Create Method. Set the method to GET.

Create API Gateway

For the integration type, you can use Mock here and save it.

Once this is done, test it. Since it’s set to Mock as the endpoint, decide what will be returned if successful.

Select Integration Response. For Mapping Template with application/json, set the value you want to return and save.

Create API Gateway

{
    "statusCode": 200,
    "message": "Hello Amazon API Gateway"
}

Let’s actually test it. If the test is successful, the response value above will be returned.

Create API Gateway

Once you reach this point, the next step is deployment.

From Actions, select Deploy API, and in the new stage, set the stage name to something like test. Then, deploy it.

After deployment, the Invoke URL will be displayed, so click on it to confirm that the response value is returned.

Create API Gateway

Try GET with FetchApi

Now, let’s try to call the API Gateway we just created using FetchApi from the local environment.

Remember to import node-fetch to use FetchApi in node.js. If you forget, you’ll encounter ReferenceError: fetch is not defined.

const fetch = require("node-fetch");

getData(`https://123456.execute-api.ap-northeast-1.amazonaws.com/test`)
    .then(data => console.log(JSON.stringify(data)))
    .catch(error => console.error(error));

function getData(url = ``, data = {}) {
    return fetch(url, {
        method: "GET"
    })
    .then(response => response.json());
}

If you run it as a test, you should correctly receive the message Hello Amazon API Gateway.

See Also