Defining New API Gateway Resources
Lab Steps
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:
Copy 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:
- Create a new API in Amazon API Gateway and define the model explained above
- Create associated API resources and methods
- Deploy the API
Â
Instructions
1. In the AWS Management Console search bar, enter API Gateway, and click the API Gateway result under Services:Â
Â
3. In the Choose an API type form, click Build in the REST API card:
You may see a dialog box welcoming you to Amazon API Gateway, click OK to proceed.
Â
4. In the Create new API form, select New API and enter the following values:
- API name:Â ItemsAPI
- Description:Â Cloud Academy Lab API
- Endpoint Type: Regional (hover over the i tooltip to learn about the different types. Regional is all this Lab requires)
Â
5. Click Create API.
The API is now created and you can define a model for it.
Â
6. Click API: ItemsAPI > Models in the left navigation panel and click Create to define a new API Gateway model:
Â
7. In the New Model form, enter the following values and then click Create model:
- Model name:Â Item
- Content type: application/json
- Model schema:
Copy code
1 2 3 4 5 6 7 8 9 10
{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "Item Schema", "type": "object", "properties": { "ID": { "type": "number" }, "name": { "type": "string" }, "price": { "type": "number" } } }
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 name:Â Items
- Content type:Â application/json
- Model schema:
Copy code
1 2 3 4 5 6
{ "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*)):
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 Name:Â Items
- Resource Path:Â items
- Enable API Gateway CORS: unchecked
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 checkmark to confirm.
Â
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:
Â
15. Click the right arrow to expand the 200 response status, expand the Mapping Templates section and click Add mapping template. Enter application/json and click the check mark to create mapping template. Here you can automatically generate a mapping template by selecting the Items model from the drop-down menu in the Generate template field:
 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:
Copy 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 blue and grey Save buttons.
Â
18. At the top of the panel, click on <-Â Method Execution to return to the diagram:
Â
19. Click TEST to open the Method Test form, and then at the bottom, click the Test button:
The response should resemble the following:
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 Actions > Create Resource.
Â
21. In the New Child Resource form, enter the following values and then click Create Resource:
- Configure as proxy resource: unchecked
- Resource Name:Â Item
- 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 means 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:
Â
23. Click Integration Response and modify Mapping Templates of the 200 response status to the following:
Copy 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:
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 name:Â dev
- Stage description:Â Development environment
- Deployment description: Only mock items list
The API is now deployed and ready to serve requests at the /items and /items/{ID}Â endpoints in the dev stage/environment.
Note: You may see a warning notification that your user does not have ListWebACLs and AssociateWebACL permissions for Web Application Firewall (WAF Regional). Use of a Web Application Firewall is not required for this lab. You may see this warning several times during the lab. The warning can be safely ignored.
Â
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:
- Creating a model
- Creating API resources
- Creating API resource methods using a mock backend integration
- 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.