A Serverless REST API in Minutes with the Serverless Framework

Development

The Serverless Framework (previously known as JAWS) debuted several months ago and has been rapidly maturing to help engineers build scalable applications without the hassle of maintaining servers.

The Framework relies exclusively on Amazon Web Services’ Lambda technology to run your code in the cloud. Lambda is unique in that it containerizes your code and auto-scales those containers for you, with zero administration required from developers. For clarity, “serverless” means the developer does not have to think about servers, even though they exist. AWS handles them. Plus, Lambda only charges you when your code is run, which is an attractive pricing model.

Overall, Lambda is possibly the most efficient resource available in the cloud for running applications. Myself and the full-time team behind the Serverless Framework believe AWS Lambda will be the focal point of the AWS cloud in the future, so we’ve designed the Framework to interpret AWS from the perspective of Lambda.

The Framework seeks to build on Lambda’s benefits and offer a familiar development experience despite Lambda’s nuances. Structure, best practices, optimization, and automation are built in. Further, the Framework allows you to decide how to containerize your logic. You can fit an entire microservice into Lambda or take a nanoservices approach and isolate the logic for each REST API endpoint in its own Lambda function. The result is unprecedented agility.

Now, let’s get a REST API up and running quickly with the Serverless Framework by using a starter/boilerplate project called the Serverless Starter.

Preparation

The Serverless Framework is one of the first application frameworks that manages both your application code as well as your infrastructure. First, you will need to give it Access Keys for your AWS account.

  • Log in or sign up for a new AWS account.
  • Navigate to the Identity & Access Management (IAM) service and create a new User called serverless-admin.
  • Copy the Security Credentials in a safe place (i.e., Access Key ID and the Secret Access Key).
  • Assign the “AdministratorAccess” policy to this User. (Later, you can reduce the permissions this IAM User has for security reasons.

access keys to AWS account

Installation

Next, make sure you have Node.js v4 or greater installed and then install the Serverless Framework via npm using this command:

$ npm install serverless -g

The Framework takes the form of a CLI, creating scaffolding, automating tasks, performing concurrent deployments, and more.

Note that we work closely with multiple teams at AWS to implement best practices. Using the Framework offers you years of AWS expertise and best practices, out of the box.

The CLI can also install existing Serverless Projects that have been published as npm packages. To install the Serverless Starter project, run this:

$ serverless project install serverless-starter

You’ll be prompted for some information to customize this project and make it your own. Be sure to enter a globally unique domain, which will be used to name an AWS S3 Bucket that’s automatically created for your project on installation. This bucket stores backups of project information that can be shared across your team. Finally, enter the Access Keys you created in the steps above.

Once you’ve finished the prompts, the following will happen:

  • The Serverless Project will be downloaded and renamed.
  • Serverless Plugins used by the Project will be installed.
  • A project “development” stage and region will be initialized.
  • An IAM Role will be created for your Project; its Lambda functions will use it to access other AWS resources in your account (e.g., a DynamoDb table).

Install dependences

Architecture

The Serverless Framework is designed to help you share code across your Lambda functions. It does this by including the functions’ parent folders and any code those parent folders hold within the deployed package.

The top level of these parent folders are called Serverless Components, and they exist in the root of your project. When you deploy any of your project’s functions, each function zips up its entire parent component. That is what’s uploaded to AWS.

In the installed Project, you will see a folder entitled restApi. This is a Serverless Component. If you look inside it, you will see the following folders:

  • lib. This is code shared across all of your functions.
  • multi. This is a Serverless Module (a folder that contains related Lambda functions). There are multiple Lambda functions in this module, each with a single REST API endpoint. You can see a function’s endpoints by looking at their s-function.json file. This is one way you can architect your REST API endpoints.
  • single. This is another Serverless Module, containing only one Lambda function. However, this Lambda has multiple REST API endpoints associated with it. This single Lambda reads the HTTP method of the incoming request and performs logic accordingly. This is another way you can architect your REST API endpoints.

serverless-starter (project)
|- _meta
|- node_modules
|- restApi (component)
   |- lib
   |- node_modules
   |- multi (module)
      |- create (function)
      |- show (function)
   |- single (module)
      |- all (function

Local Development

To run your functions locally, you can use the following command. Make sure you enter the path to your function as a parameter:

$ serverless function run restApi/single/all

This command runs your functions locally and emulates the AWS Lambda environment.

Deployment

Let’s deploy your Lambda functions using the Serverless deployment dashboard. Run:

$ serverless dash deploy

This will display an interactive screen, listing all of the functions and endpoints in your component. Use the arrow keys and press Enter next to each asset you want to deploy.

Serverless Framework

Then hit Enter next to Deploy, and the following will happen:

  • The Framework will make copies of the component for each Lambda function you’ve toggled for deployment.
  • This project comes with the Serverless Optimizer Plugin, which will browserify and minify your component’s code for each Lambda function, reducing their file size and improving their response times.
  • The Framework will compress and back up each Lambda function to your Project Bucket on AWS S3 with a timestamp, as well as upload the compressed files directly to AWS Lambda.
  • Your deployed Lambda functions on AWS will be automatically versioned and aliased to the Project stage you target during deployment (likely your “development” stage).
  • The endpoints you selected for deployment will be provisioned on AWS API Gateway and connected to their respective Lambda functions.

After deployment has finished, you will be presented with AWS ARNs for your Lambda functions, as well as URLs for any endpoints you deployed.

You’re done! Your serverless REST API is up and running. It’s massively scalable, and it charges you only when it’s called. It doesn’t get more efficient than that.

We believe good developer tools are completely extensible. So, we’ve spent countless hours refactoring the codebase so that you can replace or extend it via Serverless Plugins. A handful of plugins have already been created by our community, and any specific functionality that you require for your workflow can be easily added.

For more information on all of the above, please check out our Documentation. Nothing makes us happier than a positive tweet or a GitHub star. Also, we build this project live in our Gitter chat room. Please join the chat room for live updates, good people and support. See you in the serverless future!

Subscribe via Email

Over 60,000 people from companies like Netflix, Apple, Spotify and O'Reilly are reading our articles.
Subscribe to receive a weekly newsletter with articles around Continuous Integration, Docker, and software development best practices.



We promise that we won't spam you. You can unsubscribe any time.

Join the Discussion

Leave us some comments on what you think about this topic or if you like to add something.

  • Pingback: A Serverless REST API in Minutes with the Serverless Framework-IT大道()

  • Pingback: This week in API land #39 | Restlet - We Know About APIs()

  • Pingback: 15-02-2016 - wut more links? - Magnus Udbjørg()

  • Pingback: NODE WEEKLY NO.124 – ENUE()

  • rsweetland

    Fantastic. We have been considering Lambda for some of our core future components, but the plumbing around testing, deployment are so cumbersome. This framework changes a lot of things! Thank you for creating it (and to CodeShip for helping to spread the word!)

  • Billy

    This a really interesting concept. What about the 100 concurrent executions limit though? It seems if you are running an entire REST API via Lambda it would be quite easy to reach that limit?

    • rsweetland

      I believe this limit is just a safety net for those new to the system (ex: infinite loops spawning millions of instances). You can request a rate increase here: http://docs.aws.amazon.com/lambda/latest/dg/limits.html

      • Billy

        Ah ok thanks @rsweetland:disqus!

        • @disqus_z8bdqBq0KD:disqus it also depends on the workload. Many of the requests will be _really_ short lived. For those that are long if, as an example, you have events triggered by SNS, AWS can do automatic retries if a request fails.

  • I’d love to see a follow-up on how to add real-time features to serverless.

    • @cayblood:disqus do you mean web socket based connections? API Gateway doesn’t allow that currently I believe. Perhaps a hybrid with something like Firebase, Syncano, etc. which would also be needed to get around the short (5 minute max) lifetimes of lambda instances.

  • François Zaninotto

    I get a 404 response on the Documentation hyperlink in your article

  • Pingback: When 900 links, you reach… Look as good, you will not. - Magnus Udbjørg()

  • Fernando MG

    Excellent, it would be great one with Amazon Cognito, S3 and DynamoDB

  • Bryan C

    `npm install -g serverless`
    `serverless project install serverless-starter`
    yields:
    command “project” not found.

    I need advice on this

    • Ohstopityou

      Serverless got updated to beta. So there have been quite a lot of changes.

      serverless create –template aws-nodejs or sls create -t aws-nodejs will help you get started.

      Documentation can be found on github.

  • james w

    if you are having issues with figuring out Serverless, check here:
    https://gitter.im/serverless/serverless