Use the GET method of FetchApi to call 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:
From Actions, select Create Method. Set the method to GET
.
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.
{
"statusCode": 200,
"message": "Hello Amazon API Gateway"
}
Let’s actually test it. If the test is successful, the response value above will be returned.
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.
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
.