Embedded Analytics Tutorial

with Amazon QuickSight

Module Five: API Gatway and Static Web Page

In this module we will continue to setup the web portal.

Introduction

In this module, we will continue to setup the web portal by creating an API gateway to invoke the Lambda function and write and load the HTML static page in the S3 bucket.

What You Will Learn

  • Create API Gateway - To invoke Lambda functions.
  • Create Static Web Page

 Time to Complete

20 minutes

 Services Used

Implementation

  • Create API Gateway

    Let’s next setup an API Gateway to invoke the QSGetEmbedUrl Lambda function.

    1. Launch API Gateway and click Create API button.

    114

    2. Scroll down to REST API and click Build button.

    115

    3. Set API Name as QSGetEmbedUrlApi and click Create API button.

    116

    4. Click Actions drop down and click Create Resource option.

    117

    5. Set the following values.
    Resource Name: GetEmbedUrl
    Enable API Gateway CORS: Checked
    Click Create Resource button

    118

    6. Click Actions drop down (with getembedurl resource selected) and click Create Method option.

    119

    7. Select GET from the option box and click the tickmark icon.

    120

    8. Set the following values.
    Integration Type: Lambda Function
    Use Lambda Proxy Integration: Checked
    Lambda Function: QSGetEmbedUrl
    Click Save button

    121

    9. Click OK button in the Add Permission dialog box.

    122

    10. Click Actions drop down and click Deploy API option.

    123

    11. Make following selections.
    Deployment stage: Select [New Stage]
    Stage name: test
    Click Deploy button

    124

    12. Save the Invoke URL into your notepad as API Gateway URL

    125
  • Create Static Web Page

    We will now create a static html page and load it into our S3 bucket.

    1. Copy the following html code into a file and name it qsembed.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <script type="text/javascript" src="https://unpkg.com/amazon-quicksight-embedding-sdk@1.0.2/dist/quicksight-embedding-js-sdk.min.js"></script>
        <title>Embedding demo</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <script src="https://sdk.amazonaws.com/js/aws-sdk-2.517.0.min.js"></script>
        <style>
          iframe {border: 0;}
          body {margin:0;}
        </style>
        <script>
          var awsData = {
            dashboardId: '',
            dashboardRegion: '',
            apiGatewayUrl:'<apiGatewayUrl>?',
            cloudFrontUrl:'<cloudFrontUrl>',
            cognitoUrl:'<cognitoUrl>/login?client_id=<clientId>&response_type=token&scope=openid+profile&redirect_uri=<cloudFrontUrl>/qsembed.html',
            debug: false
          }
    
          $(document).ready(function () {
            document.getElementById('logo').src = awsData.cloudFrontUrl+'/logo.png'
            //On redirect from Cognito; Read out  state
            //Setting client and dashboard id in url is just for demo implementation.
            awsData.dashboardId = getParameterValues('dashboardid','?','&');
            awsData.dashboardRegion = getParameterValues('dashboardregion','?','&');
    
            //Get OpenIdToken
            var tokenPromise = getOpenIdToken();
    
            tokenPromise.then(function(idToken) {
              apiGatewayGetEmbedUrl(
                awsData.apiGatewayUrl,
                awsData.dashboardId,
                awsData.dashboardRegion,
                idToken
              );
            },
            function(err)
            {
                   console.log(err);
            });
          });
    
          function writeDebugInfo(debugInfo){
                  // console.log(debugInfo);
          }
    
          function getCookie(name) {
            var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
            return v ? v[2] : null;
          }
    
          function setCookie(name, value) {
            document.cookie = name + "=" + value ;
          }
    
          function getParameterValues(param,slicer,delimiter) {
            var urlParms = window.location.href.slice(window.location.href.indexOf(slicer)+ slicer.length).split(delimiter);
            for (var i = 0; i < urlParms.length; i++) {
              var urlparm = urlParms[i].split('=');
              if (urlparm[0].toLowerCase() === param) {
                setCookie(param, decodeURIComponent(urlparm[1]));
                return decodeURIComponent(urlparm[1]);
              }
            }
              return getCookie(param);
          }
    
          function parseJwt (token) {
                 var base64Url = token.split('.')[1];
                var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                }).join(''));
                return JSON.parse(jsonPayload);
            }
    
          //Redirect to Cognito if user is not Signed in.
          //Cognito will redirect back to this page and then the promise will be resolved.
          function getOpenIdToken(){
            return new Promise(function(resolve,reject) {
                writeDebugInfo('In getOpenIdToken func');
                var idToken = getParameterValues('id_token','#','&');
                if (idToken ) {
              writeDebugInfo('Token found');
                }
                else {
                    writeDebugInfo('Token not found, Redirecting to Cognito');
                    window.location.href = awsData.cognitoUrl;
                }
    
            resolve(idToken);
            });
          }
    
          //Make APIGateway call to generate the embed url.
          function apiGatewayGetEmbedUrl(
            apiGatewayUrl,
            dashboardId,
            dashboardRegion,
            openIdToken
            ) {
            const parameters = {
                dashboardId: dashboardId,
                dashboardRegion: dashboardRegion,
                openIdToken: openIdToken
            }
    
            const myQueryString = $.param(parameters);
            apiGatewayUrl = apiGatewayUrl + myQueryString;
    
            const headers = { 'Content-Type' : 'application/json' }
    
            axios.get(apiGatewayUrl, { headers: headers})
              .then((response) => {
                  embedDashboard(response.data.EmbedUrl);;
              })
              .catch(function (error) {
                      writeDebugInfo(error);
                      console.log('Error obtaining QuickSight dashboard embed url.');
              });
          }
    
          //Embed the generated url into the div identified to hold the dashboard.
          function embedDashboard(embedUrl) {
              var containerDiv = document.getElementById("dashboardContainer");
              var params = {
                      url: embedUrl,
                      container: containerDiv,
                      width:"100%",
                      height:"1000px"
              };
              var dashboard = QuickSightEmbedding.embedDashboard(params);
          }
    
        </script>
      </head>
      <body>
        <div><img id='logo' src="" style="height:50px;margin-top: 10px;margin-left: 10px;padding-bottom: 10px;" /></div>
        <div id="dashboardContainer"></div>
      </body>
    </html>
    

    2. Replace the following strings in the file. (Use replace all option)
    <apiGatewayUrl>: API Gateway URL/getembedurl
    <cognitoUrl>: https://qseAwsAccountId.auth.us-east-1.amazoncognito.com
    <clientId>: Cognito App Client Id saved in notepad
    <cloudfrontUrl>: https://CloudFront Domain Name saved in notepad

    3. Right click the following aws logo and save as logo.png
    (or use your own logo file named as logo.png)

    131

    4. Launch S3, search for qseAwsAccountId and click on the bucket name.

    132

    5. Click Upload button.

    133

    6. Add qsembed.html and logo.png and click Upload button.

    134

Conclusion

You successfully completed module five! Next, lets work on user and domain setup in module six.

Was this module helpful?

QuickSight User and Domain Setup