Lab Steps

lock
Logging in to the Amazon Web Services Console
lock
Understanding RESTful APIs
lock
Defining New API Gateway Resources
lock
Creating an AWS Lambda Function Backend
lock
Versioning and Aliasing the Lambda Function
lock
Configuring the API Gateway Backend
lock
Following Best Practices for Versions, Aliases, and Stages
lock
Creating API Keys and Usage Plans
lock
Enabling CORS on API Gateway Resources
lock
Enabling API Gateway Caching and Throttling
lock
Cleaning up API Resources and Lambda Functions
live-help Need help? Contact our support team

Here you can find the instructions for this specific Lab Step.

If you are ready for a real environment experience please start the Lab. Keep in mind that you'll need to start from the first step.

Introduction

During this Lab, you will design a very simple API to read a list of items and retrieve the details of a given item by ID.

Therefore, you will define two HTTP endpoints:

  • /items/
  • /items/{ID}/

These routes are compliant with the RESTful design principles: the first endpoint lets you retrieve the full list of items, while the second one corresponds to the detail of a single item given its ID. As you can notice, the second route is defined in terms of a dynamic parameter, which is part of the URL itself. Of course, you could achieve the very same result with a query string parameter (i.e. /items/?ID=XXX), but this pattern is generally discouraged.

In order to keep your data structures well defined and your interface documented and maintainable, you can create new API Gateway Models.

Models are useful to map your API endpoints payload, via mapping templates. They are not strictly required, as you can manually define your mapping templates, but having a model will let you generate strongly-typed SDKs for your API resources and better validate your payloads.

Technically, you can define a model with a JSON Schema. For this Lab, you will define this simple model:

content-copyCopy code
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Item Schema",
"type": "object",
"properties": {
"ID": {"type" : "number"},
"name": {"type" : "string"},
"price": {"type" : "number"}
}
}

Our items will have a unique numeric ID, a string identifying its name and a numeric price. This could be an overly simplified model for a sample e-commerce application.

In this Lab Step, you will:

  1. Create a new API in Amazon API Gateway and define the model explained above
  2. Create associated API resources and methods
  3. Deploy the API

 

Instructions

1. In the AWS Console, click Services, enter API Gateway in the search barand select the API Gateway search result:

alt

 

3. In the Choose an API type form, click Build in the REST API card:

alt

 

4. In the Create new API form, select New API and enter the following values:

  • API nameItemsAPI
  • DescriptionCloud Academy Lab API
  • Endpoint Type: Regional (hover over the i tooltip to learn about the different types. Regional is all this Lab requires)

alt

 

5. Click Create API.

The API is now created and you can define a model for it.

Warning: While the creation of the Models and Resources, you could see an error which tells you User does not have ListWebACLs and AssociateWebACL permissions for Web Application Firewall (WAF Regional). Stage settings except for WAF can still be changed. Please, ignore it, it's related to the user's policy but it doesn't compromise the lab experience.

 

6. Click APIsItemsAPI > Models in the left navigation panel and click Create to define a new API Gateway model:

alt

 

7. In the New Model form, enter the following values and then click Create model:

  • Model nameItem
  • Content type: application/json
  • Model schema
    content-copyCopy code
    {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Item Schema",
    "type": "object",
    "properties": {
    "ID": {"type" : "number"},
    "name": {"type" : "string"},
    "price": {"type" : "number"}
    }
    }

alt
The new Item model is listed under Models in the left navigation panel.

 

8. Create another model for a list of items with the following values:

  • Model nameItems
  • Content typeapplication/json
  • Model schema
    content-copyCopy code
    {
    "id": "Items",
    "title": "Items",
    "type": "array",
    "items": {"$ref": "https://apigateway.amazonaws.com/restapis/YOUR_API_ID/models/Item"}
    }

Note: You need to replace YOUR_API_ID in the items JSON entry above with your actual API ID. You can find your API ID in the breadcrumb trail of the API Gateway Console (Amazon API Gateway > APIs > ItemsAPI (*YOUR_API_ID*)):

alt

You should now see both Item and Items beneath Models in the left navigation. You are now ready to create API resources and methods.

 

9. Click on Resources in the left navigation pane, then Actions > Create Resource.

Resources are the key abstraction for information in a RESTful API. You will create resources for lists of items and individual items.

 

10. In the New Child Resource form, enter the following values and then click Create Resource:

  • Configure as proxy resource: unchecked
  • Resource NameItems
  • Resource Pathitems
  • Enable API Gateway CORS: unchecked

alt

The /items resource is now selected in the Resources panel. Notice there are no methods created yet. You will add a GET method to retrieve a list of items.

 

11. Click on Actions > Create Method and select GET from the drop-down menu. Then click the check mark to confirm.

alt

 

12. In /items - GET - Setup form set the Integration type to Mock and click the Save button.

The mock integration allows you to define API resources and methods whenever you don't have a real backend implementation yet. The advantage of this is that you can now use the Items model previously created to generate fake data. For example, this would allow you to provide a temporary API endpoint to your frontend/mobile developer, even before you have a real implementation.

 

13. In the Method Execution diagram, click on Integration Response:

alt

 

15. Click the right arrow to expand the 200 response status, expand the Mapping Templates section and click on application/json. Here you can automatically generate a mapping template by selecting the Items model from the drop-down menu in the Generate template field:

alt

 AWS generates a mapping template with random fake data, based on your JSON Schema. Given that the model defines a list, the template generates a foreach loop, which can be customized before saving.

 

16. Overwrite the generated template with the following sample code to generate a list of 3 Item objects, with different IDs, prices and names:

content-copyCopy code
[
#foreach($ID in [1, 2, 3])
#set($price = $ID * 1.5)
#set($name = "foo" + $ID)
{
"ID" : $ID,
"name" : "$name",
"price" : $price
}
#if($foreach.hasNext),#end
#end
]

 

17. Click the Save button.

 

18. At the top of the panel, click on <- Method Execution to return to the diagram:

alt

 

19. Click TEST to open the Method Test form and then click the Test button:

alt

The response should resemble the following:

alt
The method returns the template you defined. You will now define an API resource for individual items with the /items/{ID} path.

 

20. Select /items in the Resources panel and click ActionsCreate Resource.

 

21. In the New Child Resource form, enter the following values and then click Create Resource:

  • Configure as proxy resource: unchecked
  • Resource NameItem
  • Resource Path{ID}
  • Enable API Gateway CORS: unchecked

You only need to insert the {ID} part of the path since /items is automatically added when creating a new resource with /items selected in the resource panel. This makes the Item resource is a child of the Items resource. The {ID} path variable makes the path dynamic. This way, API Gateway will treat any value as a dynamic ID and pass it to the backend implementation, which will return the corresponding data.

 

22. Create a GET method with a Mock integration:

alt

 

23. Modify the Integration Response Mapping Templates to the following:

content-copyCopy code
#set($Integer = 1)
#set($ID = $Integer.parseInt($input.params("ID")))
#set($name = "foo" + $ID)
#set($price = $ID * 1.5)
{
"ID" : $ID,
"name" : "$name",
"price" : $price
}

This template extracts the dynamic ID parameter, casts it to an integer and returns an Item object with fake generated data.

 

24. Test the new /items/{ID} resource as you did previously. This time you need to enter a value under {ID} before clicking the Test button:

alt

If you leave the ID field blank, an "Internal Server Error" is returned. Any integer value should return a valid JSON response. You will replace the simple Mock implementation with a real implementation in the following Lab Steps. For now, you can proceed to deploy the API with the mock backends.

25. Click Actions > Deploy API and select [New Stage] from the Deployment stage drop-down menu. Enter the following values and then click Deploy:

  • Stage namedev
  • Stage descriptionDevelopment environment
  • Deployment description: Only mock items list

alt

The API is now deployed and ready to serve requests at the /items and /items/{ID} endpoints in the dev stage/environment.

 

26. Repeat the Deploy API action from the Resources panel action again, this time creating the prod (production) stage.

 

Summary

In this Lab Step, you have deployed an API Gateway API in dev and prod stages by:

  1. Creating a model
  2. Creating API resources
  3. Creating API resource methods using a mock backend integration
  4. Deploying the API to each stage

In the next Lab Steps, you will create and implement a Lambda function as a backend of the two HTTP endpoints you have defined.