How to Create a Serverless API and use it with React app

Nadun Yashmika
the-ai.team
Published in
4 min readJan 13, 2020

What is Serverless?

Traditionally, we deploy applications to a server where we handle all the requests and responses. This method costs more than resources and time because,

1. We are charged for keeping the server up even though the server is not handling any response at that time.
2. We have to manage all the maintenance and scaling and be responsible for the uptime.
3. We are responsible for the security, the software, and hardware updates.

This distracts the developers from the main course which is to deliver the best services from the product.

This where serverless computing comes forward, where developers have to only be concerned about the code and the service provider responsible for provisioning and managing the resources. The code you want to run will be run in stateless containers and can be triggered by events like HTTP requests, database events, and file uploads. This method is also known as Function as a Service(FaaS) because we send code to run in the cloud as functions.

The following cloud solutions providers are well known for the FaaS offerings.
1. AWS — AWS Lambda
2. Microsoft Azure — Azure functions
3. Google Cloud — Cloud functions

From here onwards let’s discuss how to build an application with AWS Lambda and react.

Building a REST API with AWS Lambda

This API will consist of two methods. This will store contacts and retrieve all contacts from AWS Dynamo DB.

1. Create a Dynamo DB Table

Go to the AWS dynamo DB console and click on the create table button. Then fill the form and press the create button to create the table.

2. Create lambda functions using the AWS Lambda console

Function to create contact

After writing the code save your work. The uuid module was used here just to create a unique id.

Create a test event adding necessary parameters to test the function. You have to add the necessary permissions to the function role to write data into the database.

If you did the tasks correctly, you will pass the test.

Follow the same steps and create the getContacts lambda function.

Let’s create the API now.

3. Setup the API Gateway

Go to the AWS API Gateway console and build a REST API.

Create a resource in the API. Inside the resource create GET and POST methods for getContacts function and createContact function respectively.

Then deploy the API.

4. Create a react app to work with the API

I made the react app with create-react-app and to access the API, I used the Axios library.

I will show only the requests here and you can download the code from my Github repository.

Request to get all the contacts.

Request to create a contact

If you get any error regarding CORS, enable CORS in the API Gateway.

And this is the end of the tutorial. Hope it is informative 😁.

--

--