Session 5 | API Gateway

Turing logo

This Session's Setup

Open up the AWS Mangement Console and login to your AWS account using the admin user you created in the setup. Do not log into your root account.

At the top of your Management Console next to your username, you'll see "Ohio" listed as your region. Go ahead and change that to US East (N. Virginia).


Checklist

Logistics and Expectations

  1. This session will touch on the basics of getting up and running with API Gateway. There are so many features of API Gateway, and two hours is only enough time to build out a very basic flow. However, as always, we've included links to additional resources you can use to further your learning once you understand the fundamentals.
  2. We will not be working with authentication or authorization, API keys, usage plans, HTTPS, or data models, although API Gateway can in fact do all of these things.

Target

Agenda and Goals

  • Understand the purpose of API Gateway
  • Create GET and POST endpoints and connect them to Lambda functions
  • Host a front end static site on S3 and dynamically generate data for it using API Gateway and Lambda

AWS API Gateway icon

API Gateway Overview

From AWS:

Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST and WebSocket APIs at any scale. API developers can create APIs that access AWS or other web services as well as data stored in the AWS Cloud.

API Gateway is one of AWS's "serverless" offerings. API Gateway serves as the entry point for a client to connect with, and the backend can be any number of things as shown in AWS's diagram below:

Diagram of API gateway integration with other services

For this session, we'll expose a few endpoints that will send back JSON data to the client. It might look something like this:

  • GET /users: triggers Lambda function allUsers
  • GET /users/1: triggers Lambda function oneUser
  • POST /users: triggers Lambda function createUser

Together: API Gateway + Lambda Diagram

Before we keep going, let's create a diagram of the scenario above.

Pricing

Under free tier, you're eligible for one million API calls per month. Even after your free tier eligibility expires, API Gateway is very affordable: the first 333,000,000 requests to hit your API will cost you a total of $3.50. The next 667,000,000 will cost a total of $2.80, and the pricing decreases in bulk after that.

Serverless Benefits

Like Lambda, API Gateway scales without you having to provision resources. By default, REST APIs can handle up to 10,000 simultaneous requests per second, but that limit can be increased with a service ticket.

Deployment Stages

API Gateway supports the use of "Stages" which can be used for a variety of things:

  • Separating dev/prod endpoints
  • Separating v1, v2, v3... etc. of your API

Data Transformation

API Gateway is able to transform data both from the request to the service (like Lambda), or from the service to back out through the Gateway to the client. This is done through Mapping Templates and the use of the Velocity Template Language. There are many uses cases for mapping templates that you can read about here.

API Gateway can also be used to add or change the headers on HTTP responses.

Security

Within API Gateway, you can create API keys and use those keys for usage plans. You can also use AWS Cognito for authorization, or you can create your own custom Lambda function for authorizing users.

API Gateway supports Cross Origin Resource Sharing (CORS), which you can enable by configuring an options method that responds to browser preflight requests. This will allow JavaScript running on other domains to make requests to your API endpoint. In addition, once the actual request is made, you can configure your GET, POST, and DELETE methods to respond with the correct CORS headers.

Structuring API Gateway + Lambda

There are multiple ways to connect API Gateway and Lambda:

  • Creating one "greedy" endpoint that catches all paths and all methods. This exposes one resource that handles every request, and it's up to the backend code (Lambda, for example), to make decisions about what to do in the cases of path/method combinations.
  • Creating separate endpoints that all invoke the same Lambda function. The request would be rejected at the API Gateway level if it doesn't match a specific resource and method combination.
  • Creating separate endpoints that each invoke a separate Lambda function. The Lambda function therefore can worry just about code execution and does not have to handle HTTP request parsing.

There are pros and cons for each approach, and you can read more about different serverless architecture patterns in the additional resources section below. For today, we're going to go with the third option: one Lambda function per resource+method combination.

Lambda Proxy Integration

We will not use Lambda Proxy Integration today; however, it's a concept worth discussing. Lambda proxy integration happens when the API Gateway passes on the entire request to the Lambda function, and the Lambda function returns a fully-formed HTTP response. In this case, your Lambda function needs to know to expect HTTP data and return HTTP responses. An example of this would be hosting an Express app in a Lambda function. Express is setup to expect HTTP data and return HTTP responses.

The opposite of this is where the API Gateway handles all of the HTTP -related things, and your Lambda function just accepts data (unrelated to HTTP) and returns data (unrelated to HTTP). An example of this would be a stand-alone function that is unrelated to HTTP (like adding two numbers). The Lambda function doesn't need to worry about setting headers, status code, etc. API Gateway will take care of that.

Additional Resources


Lady programming

API Gateway Hands-On

In this section, we'll create an API with a GET and POST endpoint, enable those endpoints support CORS, and deploy our API. Make sure that you are in the N. Virginia region and that you're on the API Gateway dashboard.

Together: Lambda Function Setup

Before we set up an API, let's create three Lambda functions that we can use as our backend: allUsers, oneUser, and createUser.

These functions doesn't need to do anything right now except for return a message saying that we successfully invoked the function.

Together: Our First AWS API

This section will fully take place in the AWS Management Console. Here's an overview of what we will cover:

  • Creating an API
  • Creating resources
  • Proxy resource
  • Enabling CORS preflight
  • Creating methods for resources
  • Integrating Lambda functions
  • Lambda proxy integration
  • Testing endpoints
  • Enabling CORS for additional resources
  • Response headers for CORS
  • Deploying the API to a stage (this is an easy step to forget!)
  • test-cors.org
  • Dynamic path parameters and sending them to Lambda with integration requests: { "id": "$input.params('id')" }

Workshop: Connecting a Front End to API Gateway and Lambda

In this section, build an API Gateway that triggers Lambda functions. You'll then deploy a pre-built front-end on S3 and use it to request data from your API Gateway. Find the workshop instructions here.


Mop and bucket

Cleanup

Because of the generous free tier limits for API Gateway, S3, and Lambda, you won't be charged for your resources (unless your pet rescue site goes viral). We will be using the petRescue resources in Session 6 when we add our DynamoDB functionality, so don't delete things yet! If you'd like to delete your user resources (allUsers, createUser, oneUser), feel free.