To get our hands dirty and quickly see it working, let's deploy an API from a Swagger definition file that just uses the pre-built demo Pet Store endpoint.
Go to the API Gateway console here https://console.aws.amazon.com/apigateway/
Do either of the below (depending on your case):
If this is the first API in your account
Get Startedfrom the API Gateway console welcome page.
If this is not your first API
Create APIfrom API Gateway's APIs tab (left-hand side)
Under Create new API
, choose Examples API
(this, most likely, will already be chosen for you)
You should see an in-built swagger definition file like so (culled for brevity):
{
"swagger": "2.0",
"info": {
"description": "Your first API with Amazon API Gateway. This is a sample API that integrates via HTTP with our demo Pet Store endpoints",
"title": "PetStore"
},
"schemes": [
"https"
],
"paths": {
"/": {
"get": {
"tags": [
"pets"
],
"description": "PetStore HTML web page containing API usage information",
...
...
...
Leave the Endpoint type
chosen as Regional
(this is a new feature -- you can actually choose either for our purposes)
Scroll down and click Import
You should now see the newly created API
Now, to view the details of each HTTP API method, choose the method name from the resource tree. For example:
GET /
resource Testand see the response
GET /pets
resourceTestand see the response
Now, let's choose the POST /pets
method
To test the POST /pets
method, enter the JSON payload below into the Request Body and click Test
.
{
"type": "dog",
"price": 249.99
}
Response Bodylike below along with
Response Headersand associated logs
{
"pet": {
"type": "dog",
"price": 249.99
},
"message": "success"
}
To deploy this new API, select the PetStore API
that we just created, and then choose Deploy API
from under the Actions menu.
In the Deploy API
dialog box...
Deployment stage, select [New Stage] because this is the first deployment of the API.
Deploy
In the resulting Stage Editor
pane, the Invoke URL
displays the URL to use to invoke the API's GET /
method request.
In Stage Editor
, follow the Invoke URL link to submit the GET / method request in a browser to see the response.
In the Stages navigation pane, expand the test stage, select GET on /pets/{petId}, and then copy the Invoke URL value and paste it into a browser
If successful, you should see a response JSON like so
{
"id": 1,
"type": "dog",
"price": 249.99
}
We've just successfully created an API Gateway integreated with an HTTP bakend.
Now let's create an API Gateway to expose the functionality of one of our Lambda functions that we created in the previous workshops. Let's pick the SimpleTaxCalculator Lambda function and expose that as a service.
Configurationtab (you should be by default)
Add triggers, notice a list of potential triggers. Any of these can be used to fire off (trigger) a lambda function
Now let's pick API Gateway as a trigger for our Lambda microservice.
Click on the API Gateway
trigger
API Gatewaybelow and to the left of our
SimpleTaxCalculator-YOUR_ORG_IDlambda function
Scroll down the Configure triggers
and...
API nameclick
Enter Valueto the right and type
SimpleTaxCalculatorService-YOUR_ORG_ID
Deployment stageclick
Enter Valueand enter
prod(or dev, stage, whatever you prefer)
Security, choose
Open
Add
Save
This will have created a new API Gateway endpoint at which our SampleTaxCalculator microservice is now exposed.
Right below the title API Gateway
, you'll see a link with the name of the API Gateway that you just created (SimpleTaxCalculator-YOUR_ORG_ID).
Right-click this link to go to the API Gateway console
Click on Test
Methodchoose POST
Request Bodyand add this JSON payload
{
"productPrice": 20,
"taxRate": 10,
"surchargeRate": 1
}
Click on Test
and check the response...
Notice that this doesn't work (you should see something like this)
{
"message": "Internal server error"
}
Look at logs to see the disconnect between how a browser sends a web request and how our Lambda function expects its input. So we need to update our original Lambda microservice to understand how a browser sends a request.
'use strict';
console.log('Loading tax calculator function...');
exports.handler = (event, context, callback) => {
console.log('Received event: ', JSON.stringify(event, null, 2));
try {
let productPrice, taxRate, surchargeRate = null;
if (event.body !== null && event.body !== undefined) {
let body = JSON.parse(event.body)
productPrice = body.productPrice;
taxRate = body.taxRate;
surchargeRate = body.surchargeRate;
}
else {
productPrice = event.productPrice;
taxRate = event.taxRate;
surchargeRate = event.surchargeRate;
}
console.log(`Product price: $${productPrice}`);
console.log(`Tax rate: ${taxRate}%`);
console.log(`Surcharge rate: ${surchargeRate}%`);
let tax = productPrice * (taxRate / 100.00);
let surcharge = productPrice * (surchargeRate / 100.00);
let finalPrice = productPrice + tax + surcharge;
console.log(`Final price with tax: $${finalPrice}`);
let returnValue = {
price: finalPrice,
state: "CA"
}
var response = {
statusCode: 200,
headers: {
"x-custom-header" : "Some custom header value"
},
body: JSON.stringify(returnValue)
};
// On success, invoke the callback like so (2 arguments)
// first one being null.
callback(null, response); // Return calculated tax
}
catch(e) {
console.log(e);
// On failure, invoke the callback like so (a single argument)
// with a helpful error message.
callback('ERROR: Something went wrong!');
}
console.log("Done calculating tax.");
};
Click on Save
(top right-hand corner)
Now retry by clicking on Test
again and you should see success
To help better understand and visualize what we changed from the original SimpleTaxCalculator.js
in order to get this to work with a web request from API Gateway, I've included a diff here:
console.log('Received event: ', JSON.stringify(event, null, 2));
try {
- console.log(`Product price: $${event.productPrice}`);
- console.log(`Tax rate: ${event.taxRate}%`);
- console.log(`Surcharge rate: ${event.surchargeRate}%`);
+ let productPrice, taxRate, surchargeRate = null;
- let tax = event.productPrice * (event.taxRate / 100.00);
- let surcharge = event.productPrice * (event.surchargeRate / 100.00);
- let finalPrice = event.productPrice + tax + surcharge;
+ if (event.body !== null && event.body !== undefined) {
+ let body = JSON.parse(event.body)
+
+ productPrice = body.productPrice;
+ taxRate = body.taxRate;
+ surchargeRate = body.surchargeRate;
+ }
+ else {
+ productPrice = event.productPrice;
+ taxRate = event.taxRate;
+ surchargeRate = event.surchargeRate;
+ }
+
+ console.log(`Product price: $${productPrice}`);
+ console.log(`Tax rate: ${taxRate}%`);
+ console.log(`Surcharge rate: ${surchargeRate}%`);
+
+ let tax = productPrice * (taxRate / 100.00);
+ let surcharge = productPrice * (surchargeRate / 100.00);
+ let finalPrice = productPrice + tax + surcharge;
console.log(`Final price with tax: $${finalPrice}`);
let returnValue = {
- price: finalPrice
+ price: finalPrice,
+ state: "CA"
}
+ var response = {
+ statusCode: 200,
+ headers: {
+ "x-custom-header" : "Some custom header value"
+ },
+ body: JSON.stringify(returnValue)
+ };
+
// On success, invoke the callback like so (2 arguments)
// first one being null.
- callback(null, returnValue); // Return calculated tax
+ callback(null, response); // Return calculated tax
}
catch(e) {
console.log(e);