How to build your first Serverless API in 15 mins

Tue Oct 27 20204 min read

Why Serverless

Cloud is eating the world. The days are gone when scaling a software meant having an army of physical servers running in your data center. Now we can provision as many servers we need in real-time without owning a data center.

But with great powers’ comes great responsibilities. Now it is not enough to be a good application developer anymore, rather you need to understand the intricacies of your cloud environment before you can deploy your changes. With Serverless stack, the need to provision underlying infrastructure is taken care by the cloud provider and you can focus on what you do best i.e. building features.

Serverless Inc

Serverless Inc. is an amazing platform which provides first class developer tools and support to adopt Serverless Stack without friction. It is a write once and use anywhere declarative model, which makes it so much easier to adopt Serverless stack without worrying about the underlying plumbing.

Setting up Serverless

Setting up Serverless is very simple.

yarn global add serverless

Serverless Pro provides an amazing developer friendly, whole serverless project lifecycle management tool, which is absolutely amazing. It is free for individual developer and small teams. I strongly recommend to sign-up for it.

It comes with command-line wizard which will help you setup everything.

serverless

Setting up AWS

We will be using AWS as our cloud provider. If you don’t have an AWS account, please sign-up for a 12 month free-tier account.

Once you have your AWS account setup, follow the steps to configure your AWS with serverless.

Preparing the Project

We will be using NodeJS as our choice of language for Lambda. We will be using this amazing starter template to setup our project.

serverless install --url https://github.com/AnomalyInnovations/serverless-nodejs-starter --name serverless-hello-world

cd serverless-hello-world

yarn

Running locally

Once everything is setup, lets make sure everything is running as expected.

serverless offline start

If everything was configured properly, you should see something like this

Serverless Initial Setup

Now copy the url (http://localhost:3000/hello) and paste it in the browser or run curl You should see the below results

Initial Output

Adding url params

We should change the name of our service to make sure it is unique.

We will also like to receive a name in our url param, so that we can greet the user when they call our api.

Our serverless.yml looks like

# NOTE: update this with your service name
service: hello-world-http

# Create an optimized package for our functions
package:
  individually: true

plugins:
  - serverless-bundle # Package our functions with Webpack
  - serverless-offline
  - serverless-dotenv-plugin # Load .env as environment variables

provider:
  name: aws
  runtime: nodejs12.x
  stage: dev
  region: us-east-1
  # To load environment variables externally
  # rename env.example to .env and uncomment
  # the following line. Also, make sure to not
  # commit your .env.
  #
  #environment:
  #  SAMPLE_ENV_VAR: ${env:SAMPLE_ENV_VAR}

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello/{name}
          method: get

We will need to change the handler code as well to make sure we get the name.

export const hello = async (event, context) => {
  // Get the name from url parameters
  const name = event.pathParameters.name;

  return {
    statusCode: 200,
    body: JSON.stringify({
      message: `Hello ${name} !!! Go Serverless v2.0! ${(await message({ time: 1, copy: 'Your function executed successfully!'}))}`,
    }),
  };
};

const message = ({ time, ...rest }) => new Promise((resolve, reject) =>
  setTimeout(() => {
    resolve(`${rest.copy} (with a delay)`);
  }, time * 1000)
);

Now hitting the api again should print the user name as well.

http://localhost:3000/hello/debojit

Output after modifications

If you are seeing a similar output, then our api is working fine.

Deploying the API

Once we are happy with our api, next step is to deploy it on AWS. If you have setup your AWS credentials correctly, deploying your api is just one line effort. That’s the beauty of using Serverless Framework.

serverless deploy

Under the wraps, the framework is building and bundling your code with webpack and then creating Cloudformation stack descriptor and deploying it to AWS. If you want to check out the final output, you can look under .serverless folder.

If deployment is successful, you should see something like this

Deployment Logs

Testing everything is working

Once the deployment is complete, copy the endpoint details from logs.

A quick curl should let us know if everything is working fine.

curl https://g7d181qs7j.execute-api.us-east-1.amazonaws.com/dev/hello/debo

You should be seeing output like this

{"message":"Hello debo !!! Go Serverless v2.0! Your function executed successfully! (with a delay)"}

Congratulations !!! You have successfully built and deployed your first Serverless API.

Cleaning up

Finally lets clean-up our stack. We don’t want open api endpoints lingering around when we pay per execution. Cleaning up is also easy one-liner.

serverless remove

If everything goes well, you should see something like this.

Stack Removal Output

Conclusion

Serverless is definitely the future of computing. It is cost effective and helps you focus on building features that matter. With developer friendly software from Serverless Inc. adoption of Serverless has become much easier.

serverless

aws

lambda

api-gateway

http

Built using Gatsby