Building an API with Lambdas and API Gateway
Tags: apiintegration, movies, awslambda, apigateway
Published: 2018-08-24 13:56:03

---
title: Building an API with Lambdas and API Gateway
published: true
tags: api-integration,movies,aws-lambda,api-gateway
canonical_url: https://medium.freecodecamp.org/building-an-api-with-lambdas-and-api-gateway-11254e23b703
cover_image: https://cdn-images-1.medium.com/max/795/1*VjGHQOLK4sJDqYvzTkx30g.png
---

#### Want to access your database, control your system or execute some code from another website? An API can do all of this for you and they’re surprisingly easy to set up.


An API is a url that you can perform _GET, PUT, POST_ and _DELETE_ requests on to control another service. If you make one yourself then you can build these APIs to do whatever you want behind the scenes. Common uses are providing database control, performing actions on third party APIs (API-ception) or controlling another service.

### Why Use an API

You may ask why we need an API when we can access the database directly or run the code on the website. There are a few massive advantages to APIs over running the code in your website.

#### Hide Your Access Keys and Tokens

This is possibly the most important reason to use an API. If your are accessing a database then you’re going to need the database details as well as user and access token/key.

If you access the database from the website then you’re going to have all of these details in the source code of your site. This is really bad practice as anyone can look into the source control and steal your details. This doesn’t sound too bad but what if these are your AWS or Google Cloud Compute credentials? They could then use these to run whatever they want on your account, leaving you with a huge bill.

Running these processes from behind an API means no one can see any of the private details so can’t steal them to use in their own projects. If you store your website code in Github or another public source control then it also means that they aren’t visible there either.

#### Run the Code Elsewhere

What if you aren’t using any other services and aren’t using any secret keys? If you are running a large or complex bit of code or if you don’t want anyone else reading your code and working out how it works then you can still use an API.

#### Control Who Has Access

![](https://cdn-images-1.medium.com/max/1024/1*mXW73ujWRmuYUACsNpzKqw.jpeg)

Providing an API also allows you to restrict who is able to access the database or run the code. You can do this by requiring an API key. This key is used to identify the user making the request and then allowing or rejecting the request.

This can be used to allow only a few people to access the service, or even to create a tier system. This is how a lot of paid APIs work, giving everyone free but limited access and then allowing you to pay for access to superior parts of the service or just higher rate of requests.

### Building the API

Now that we know some reasons why we might want to create an API, lets do just that. We’re going to use API Gateway and AWS Lambdas because its simpler than running a server. Make sure you have an AWS account and are logged in.

#### Setting up API Gateway

We can start by opening the API Gateway service and clicking _Get Started\*._ On the next page we need to make sure that we’ve selected the _New API_ option and then give our API a name.

When creating our first API we should select _\*New API\*_ and then we can give this API a name and description and click _\*Create API\*_.

![](https://cdn-images-1.medium.com/max/1024/1*CjKTmP5zCWhqr_XIznAuZw.png)

Clicking _Create API_ will get us into the configuration page for your API. The first thing we need to do is to add a resource onto the API. Using resources allows us to group similar API calls together using nested slashes. We are going to create an API that we can use to recommendations on what to watch. Therefore we can have /_tv-shows_ and _/movies_ as two base methods.

Click the _Actions_ dropdown and select _Create Resource._ Name your resources, making sure that they are both in the “/” path.

![](https://cdn-images-1.medium.com/max/900/1*gj847pJH6XRgL4K-Iy2c9Q.png)

![](https://cdn-images-1.medium.com/max/1024/1*3u-krWS1HQx25aDYtyS6iA.png)

We want users to be able to go to _/movies/horror_ or _/tv-shows/comedy_ and we can do this by adding path parameters. These are variables that we can access inside the API. To create one of theses we need to set the resource to _{resourceName}_ as shown below. This can be done for _tv-shows_ and _movies._

![](https://cdn-images-1.medium.com/max/1024/1*HVNkD3aWgl5FPHw8E1U-9Q.png)

Now that we can length and genre we can create methods for getting and adding data to a table. Select one of the _{genre}_ resources and click _Actions_ then _Create Method._ This will create a small grey box below the resource which we can click. We are going to start with a _GET_ request so select that and click the tick button.

This is where we get to decide how to handle the request. We are going to use AWS Lambdas but we need to create them before we can finish setting up the methods.

#### Creating the Lambdas

We are able to respond to these API requests using Lambdas which is great as they only run when we need them to. They are also really easy to create so that’s what we’ll do now.

In the Lambda console click _Create function_ and then we can name our first API function _movieAPI,_ set it to run Node 8.10 and _Create new role from template(s)._ Name our new role _tableAPI_ and add _Simple Microservice permissions_ as the only template.

All code can be found at [https://github.com/SamWSoftware/Projects/tree/master/movieAPI](https://github.com/SamWSoftware/Projects/tree/master/movieAPI)

Click _Create function_ and we are sent into the Lambda window. Scroll down to the _Function code_ section and we’ll change the code. The first thing we’re going to do is to check what request method was used.

```
exports.handler = async (event) => {
    console.log(event);
    if (event.httpMethod === 'PUT'){
        let response = putMovie(event)
        return done(response);
    } else if (event.httpMethod === 'GET'){
        let response = getMovie(event);
        return done(response);
    }
};
```

We’re going to start by writing the _getMovie_ function. This function will start by getting the _genre_ from the path parameters. This is where using path parameters can make this process easy.

```
const getMovie = event => {
    let genre = event.pathParameters.genre;
    return;
}
```

With the genre that the user requested we are going to get a recommended movie for them. I copied these from [25 Top Films From Each Genre](https://www.imdb.com/list/ls000441429/) and added them to an object with the genre as the key. We can then get the film by getting the value of the genre requested.

```
const movies = {
    action: 'Desperado (1995)',
    fantasy: 'Inception (2010)',
    ...
    horror: 'Black Swan (2010)'
}

const getMovie = event => {
    let genre = event.pathParameters.genre;
    return movies[genre];
}
```

This means that the title of the movie is being passed into the _done_ function. This function is used as API Gateway expects the data to come back in a very specific format. This function turns a string into that required format.

```
const done = response => {
    return {
        statusCode: '200',
        body: JSON.stringify(response),
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Methods': '\*',
            'Access-Control-Allow-Origin': '\*'
        }
    }
}
```

We can do a very similar thing for a _tv-showsAPI_ function, reusing most of the code, just changing the function names and the movie suggestions to tv show.

#### Connecting the Lambdas to API Gateway

Back in API Gateway we can add our new Lambdas to the methods we created earlier. We need to make sure that _Use Lambda Proxy integration_ is selected and we are pointing at the correct Lambda. Clicking _Save_ will ask you for permissions to access this Lambda which we can give the _OK._

![](https://cdn-images-1.medium.com/max/1024/1*p_tMRh17u0KxXOMyA6OFvQ.png)

Do this for the _GET_ methods on both resources and we can start to test. Selecting the methods should now show a method execution diagram. This sounds complicated but the only bit we need is the _TEST _section.

Clicking TEST will open a new section where we can try out the API. There are lots of things you can set here but the only one we care about is the _Path {genre}._ We need to set this to the genre we’re requesting. Entering _western_ as the genre and hitting the _Test_ button gets a response like this:

![](https://cdn-images-1.medium.com/max/1024/1*bHaxGw8vv1XmQUK2TJBkAQ.png)

We got our API working! Now we need to make sure that other people can access it. There are two steps to this.

1. We enable CORS — Select the _{genre}_ resource and then click _Actions_ and _Enable CORS._ Leave everything as defaults and when asked click _Yes, replace existing values._
2. Deploy our API — Click on _Actions_ and _Deploy API_. Set the deployment stage to _[New Stage]_ and then give your stage a name like _production_ or_ public._

Once your API has deployed you should get a URL like this. This is the base of your API. You can add /movies/western to access your API.

```
https://{uniqueCode}.execute-api.eu-west-1.amazonaws.com/production
```

That’s all for this article but in the next one we’ll connect this API to Dynamo tables and let users vote on their favourite movies in each genre.

If you’ve liked this article, make sure to hit that like button and follow me for the next API article.


* * *