Create & Interact with a Serverless REST API with AWS Lambda from React

nader dabit
Instructornader dabit
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

In this lesson we’ll learn how to create a Lambda function and use AWS Amplify to interact with the Lambda function from a React app. Lambda functions allow us to easily create one off functionality or interact with microservices. We’ll use the Lambda function to translate text from english to spanish.

Instructor: [00:02] To add a REST API using a AWS Lambda function, we can run the amplify add API command. For the type of service, we'll choose rest. The API that we'll be creating will be fetching a list of people. We'll call the API PeopleAPI. For the path, we'll give it a path of /people.

[00:26] For the Lambda function data source, we'll create a new Lambda function. Next, we're asked for a label for the Lambda function. We'll call this peoplefunction. For the name of the Lambda function, we'll also call it peoplefunction. For the function template that we'd like to use, we'll use a Serverless Express function.

[00:47] Next, we'll be asked if we'd like to edit the local function now. We'll choose yes. This should open up amplify/backend/function/peoplefunction/source/app.js in our text editor.

[01:01] In App.js, we'll see the code for our Lambda function. We'll scroll down until we see app.get/people. Right now, /people is returning an object with the success property and a URL. We'll go ahead and create a new array called people and hard-code some data.

[01:35] Next, we'll update the response to return the array of people. Save this file and drop back to the command line. We're next asked if we'd like to restrict API access. Since we have authentication enabled, we'll choose yes. For access, we'll give authenticated users only access. For the type of access, we'll choose read.

[02:02] With the local configuration created, we can run amplify push to push the new configuration to our account and create the resources. Once the resources have been created, open up App.js. Here, we'll first import API from AWS Amplify.

[02:29] In our class definition, we'll define an initial state of people and set it to an empty array. We'll create a componentDidMount lifecycle method that we'll call API.get. Here we'll pass in the name of the API as well as the path that we would like to fetch.

[02:54] The data returned from the API will be an object with an array of people. When the data is returned from the API, we'll call this.setstate, setting the value of people to data.people.

[03:16] In our render method, we'll map over the people array, showing the person's name as well as the hair color for every item in the array.

[03:31] Now we'll save the file, and we'll run npm start to launch the app.

[03:39] If everything is working properly, we should see the data rendered to our screen. Right now, our API is only returning hard-coded data. Let's update the API to fetch data from a third-party API. To do so, we're going to need to install the Axios package to send HTTP requests. Change into amplify/backend/function/peoplefunction/source.

[04:06] From within this directory, we'll go ahead and install the Axios package. We'll next open App.js from the backend/function/peoplefunction/source folder. Here, we'll first require Axios from the Axios package.

[04:38] We'll then call Axios.get, passing in the URL for the open source Star Wars API. Axios will return a promise. We'll set a .then and a .catch function. If there's an error, we'll return a JSON object containing an error property and setting people to null.

[05:10] If it's successful, we'll go ahead and create a new variable called people, setting it to response.data.results. We'll then return a JSON object with an error property set to null along with the people array.

[05:32] Since we've made changes to our Lambda function, we're going to need to run amplify push again.

[05:43] Once the resources have been updated in your account, we'll run npm start to restart the React app. When the app loads, we should now see the data being returned from the Star Wars API.

Gerardo
Gerardo
~ 6 years ago

Thanks Nader, as always amazing explanations. Just found 2 small typos on the code:

  1. An extra dot at the Const declaration const.people = [ ]
  2. An extra semicolon in the Axios success response people:
Gerardo
Gerardo
~ 6 years ago

Note: the typo is in the transcripted code, not on the code in the video.

moshe pinhasi
moshe pinhasi
~ 6 years ago

This is a great video!

Can I serve static from the backend function (for server side rendering case)? If yes, how can I do that? where should I put the static files?

nader dabit
nader dabitinstructor
~ 6 years ago

Can I serve static from the backend function (for server side rendering case)? If yes, how can I do that? where should I put the static files?

Yes, you can do this. As long as the files are located in the main project root, it should work. Gatsby is a popular use case for this.

Ben
Ben
~ 6 years ago

AppSync now has functions

Babs Craig
Babs Craig
~ 6 years ago

Ran into an issue where the amplify push command didn't work after setting up the api. I ran amplify-init again and this seemed to solve the issue. In case you also run into it, find reference here: https://github.com/aws-amplify/amplify-cli/issues/195

Luis
Luis
~ 6 years ago

I get a 502 while making a get call on peopleapi. Would anyone be able to help

Luis
Luis
~ 6 years ago

never mind it was a silly mistake on my end

Eyas Tayyem
Eyas Tayyem
~ 5 years ago

I keep getting a 403 Error message Access to XMLHttpRequest at 'https://8w9xad2in3.execute-api.us-west-2.amazonaws.com/amplifyapp/people' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I've created a user with an authentication token and signed in. Any idea what could be the issue here?

Xavier Brinon
Xavier Brinon
~ 5 years ago

https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

Joe Seifi
Joe Seifi
~ 5 years ago

I'm running into an issue with authentication enabled, and getting a 403 on the endpoint. In API Gateway I am seeing "Auth: AWS_IAM" for both of the ANY endpoints, and I am logged into the app using the withAuthenticator HOC. Seems like somehow the app isn't either looking for the logged in token, not passing it, or not honoring it.

Any ideas?

Mateusz Angulski
Mateusz Angulski
~ 5 years ago

CORS is set up by default in app.js in the express app. It's the issue with aws role not having access to the execute-api:Invoke action. Please try to do the failing GET request in postman or curl and there you can see what role is missing which action for what resource. In my case it was adding this policy to one of the roles: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-iam-policy-examples-for-api-execution.html First one at the top.

Mason Jennings
Mason Jennings
~ 4 years ago

Looks like the star wars api address has been updated to swapi.dev

Markdown supported.
Become a member to join the discussionEnroll Today