Getting Started with AWS

Build a Serverless Web Application

with AWS Lambda, Amazon API Gateway, AWS Amplify, Amazon DynamoDB, and Amazon Cognito

Module 4: Deploy a RESTful API

You will use Amazon API Gateway to expose the Lambda function you built in the previous module as a RESTful API

Overview

In this module, you will use Amazon API Gateway to expose the Lambda function you built in the previous module as a RESTful API. This API will be accessible on the public Internet. It will be secured using the Amazon Cognito user pool you created in the previous module. Using this configuration, you will then turn your statically hosted website into a dynamic web application by adding client-side JavaScript that makes AJAX calls to the exposed APIs.

Architecture overview

The diagram above shows how the API Gateway component you will build in this module integrates with the existing components you built previously. The grayed out items are pieces you have already implemented in previous steps.

The static website you deployed in the first module already has a page configured to interact with the API you will build in this module. The page at /ride.html has a simple map-based interface for requesting a unicorn ride. After authenticating using the /signin.html page, your users will be able to select their pickup location by clicking a point on the map and then requesting a ride by choosing the "Request Unicorn" button in the upper right corner.

This module will focus on the steps required to build the cloud components of the API, but if you're interested in how the browser code works that calls this API, you can inspect the ride.js file of the website. In this case, the application uses jQuery's ajax() method to make the remote request.

 Time to complete

15 minutes

 Services used

Implementation

    1. In the Amazon API Gateway console, select APIs in the left navigation pane. 
    2. Choose Build under REST API. 
    3. In the Choose the protocol section, select REST
    4. In the Create new API section, select New API.
    5. In the Settings section, enter WildRydes for the API Name and select Edge optimized in the Endpoint Type dropdown.
      Note: Use edge-optimized endpoint types for public services being accessed from the Internet. Regional endpoints are typically used for APIs that are accessed primarily from within the same AWS Region.
    6. Choose Create API.
  • You must create an Amazon Cognito User Pools Authorizer. Amazon API Gateway uses JSON web tokens (JWT), which are returned by the Amazon Cognito User Pool (created in Module 2) to authenticate the API calls. In this section, we will be creating an Authorizer for the API, so we can make use of the user pool.

    Use the following steps to configure the Authorizer in the Amazon API Gateway console:

    1. In the left navigation pane of the WildRydes API you just created, select Authorizers.
    2. Choose Create New Authorizer
    3. Enter WildRydes into the Authorizer Name field.
    4. Select Cognito as the Type
    5. Under Cognito User Pool, in the Region drop-down, select the same Region you have been using for the rest of the tutorial. Enter WildRydes in the Cognito User Pool name field. 
    6. Enter Authorization for the Token Source
    7. Choose Create.
    8. To verify the authorizer configuration, select Test
    9. Paste the Authorization Token copied from the ride.html webpage in the Validate your implementation section of Module 2 into the Authorization (header) field, and verify that the HTTP status Response code is 200. 

     

     

  • In this section you will create a new resource within your API. Then create a POST method for that resource and configure it to use a Lambda proxy integration backed by the RequestUnicorn function you created in the first step of this module.

    1. In the left navigation pane of your WildRydes API, select Resources.
    2. From the Actions dropdown, select Create Resource.
    3. Enter ride as the Resource Name, which will automatically create the Resource Path /ride.
    4. Select the checkbox for Enable API Gateway CORS.
    5. Choose Create Resource.
    6. With the newly created /ride resource selected, from the Actions dropdown select Create Method.
    7. Select POST from the new dropdown that appears under OPTIONS, then select the checkmark icon.
    8. Select Lambda Function for the Integration type.
    9. Select the checkbox for Use Lambda Proxy integration.
    10. Select the same Region you have been using throughout the tutorial for Lambda Region.
    11. Enter RequestUnicorn for Lambda Function.
    12. Choose Save.
      Note: If you get an error that your function does not exist, check that the region you selected matches the one you used in the previous modules.
    13. When prompted to give Amazon API Gateway permission to invoke your function, choose OK.
    14. Select the Method Request card.
    15. Choose the pencil icon next to Authorization.
    16. Select the WildRydes Cognito user pool authorizer from the drop-down list, and select the checkmark icon.
  • In this section you will deploy your API from the Amazon API Gateway console. 

    1. In the Actions drop-down list select Deploy API.
    2. Select [New Stage] in the Deployment stage drop-down list.
    3. Enter prod for the Stage Name.
    4. Choose Deploy.
    5. Copy the Invoke URL. You will use it in the next section.
  • In this step you will update the /js/config.js file in your website deployment to include the Invoke URL of the stage you just created. You will copy the Invoke URL directly from the top of the stage editor page on the Amazon API Gateway console and paste it into the invokeUrl key of your site's config.js file. Your config file will still contain the updates you made in the previous module for your Amazon Cognito userPoolID, userPoolClientID, and region.

    1. On your local machine, navigate to the js folder, and open the config.js file in a text editor of your choice
    2. Paste the Invoke URL you copied from the Amazon API Gateway console in the previous section into the invokeUrl value of the config.js file. 
    3. Save the file.

    See the following example of a completed config.js file. Note, the actual values in your file will be different.

    window._config = {
    
        cognito: {
    
            userPoolId: 'us-west-2_uXboG5pAb', // e.g. us-east-2_uXboG5pAb         
    
            userPoolClientId: '25ddkmj4v6hfsfvruhpfi7n4hv', // e.g. 25ddkmj4v6hfsfvruhpfi7n4hv
    
            region: 'us-west-2' // e.g. us-east-2 
    
        }, 
    
        api: { 
    
            invokeUrl: 'https://rc7nyt4tql.execute-api.us-west-2.amazonaws.com/prod' // e.g. https://rc7nyt4tql.execute-api.us-west-2.amazonaws.com/prod, 
    
        } 
    
    };

        3. Add, commit, and push the updated config.js file to your Git repository to have it automatically deploy to Amplify Console.

    $ git add .
    $ git commit -m "new_configuration"
    $ git push
    
  • Note: It is possible that you will see a delay between updating the config.js file in your S3 bucket and when the updated content is visible in your browser. You should also ensure that you clear your browser cache before executing the following steps.

    1. Update the ArcGIS JS version from 4.3 to 4.6 (newer versions will not work in this tutorial) in the ride.html file as:
    <script src="https://js.arcgis.com/4.6/"></script>
     <link rel="stylesheet" href="https://js.arcgis.com/4.6/esri/css/main.css">

    An example of a complete ride.html file is included below. Note, some values in your file may be different.

    <div id="noApiMessage" class="configMessage" style="display: none;">
            <div class="backdrop"></div>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Successfully Authenticated!</h3>
                </div>
                <div class="panel-body">
                    <p>This page is not functional yet because there is no API invoke URL configured in <a href="/js/config.js">/js/config.js</a>. You'll configure this in Module 3.</p>
                    <p>In the meantime, if you'd like to test the Amazon Cognito user pool authorizer for your API, use the auth token below:</p>
                    <textarea class="authToken"></textarea>
                </div>
            </div>
        </div>
    
        <div id="noCognitoMessage" class="configMessage" style="display: none;">
            <div class="backdrop"></div>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">No Cognito User Pool Configured</h3>
                </div>
                <div class="panel-body">
                    <p>There is no user pool configured in <a href="/js/config.js">/js/config.js</a>. You'll configure this in Module 2 of the workshop.</p>
                </div>
            </div>
        </div>
    
        <div id="main">
            <div id="map">
            </div>
        </div>
    
        <div id="authTokenModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="authToken">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Your Auth Token</h4>
                    </div>
                    <div class="modal-body">
                        <textarea class="authToken"></textarea>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    
    
        <script src="js/vendor/jquery-3.1.0.js"></script>
        <script src="js/vendor/bootstrap.min.js"></script>
        <script src="js/vendor/aws-cognito-sdk.min.js"></script>
        <script src="js/vendor/amazon-cognito-identity.min.js"></script>
        <script src="https://js.arcgis.com/4.6/"></script>
        <script src="js/config.js"></script>
        <script src="js/cognito-auth.js"></script>
        <script src="js/esri-map.js"></script>
        <script src="js/ride.js"></script>
    </body>
    
    </html>

        2. Save the modified file. Add, commit, and git push it to your Git repository to have it automatically deploy to AWS Amplify console.

        3. Visit /ride.html under your website domain.

        4. If you are redirected to the ArcGIS sign-in page, sign in with the user credentials you created previously in the Introduction section as a prerequisite of this tutorial.

        5. After the map has loaded, click anywhere on the map to set a pickup location.

        6. Choose Request Unicorn. You should see a notification in the right sidebar that a unicorn is on its way and then see a unicorn icon fly to your pickup location.

Was this page helpful?

Resource Cleanup