Getting started with Serverless Framework

yash kumar shah
5 min readAug 17, 2020

Major Startup during the Initial phase face the challenges of Rapid Development. They need a huge line of code to make few products working in market and making them available for the user thus improving further according to feedback and usage.

Serverless is one of the framework which is the fastest way to develop API’s where developer don’t have to worry for the underlying hardware requirement to run the application rather than have to complete focus on the development part.

So to play around serverless you must be comfortable with any of the few common language to get your code up and running without setting up any Infra.

Pre-Requisite:

There must be node setup in your local-machine and there must be an aws access setup with your local-machine with appropriate access to create and update :- cloudformation, Api-gateway, s3 and lambda.

Let’s Start

To install serverless

npm install serverless -g

I am comfortable with python so I am using python as a template but you can use any language of your choice. Some of the common templates that serverless supports are :

  • aws-clojurescript-gradle
  • aws-clojure-gradle
  • aws-nodejs
  • aws-nodejs-typescript
  • aws-alexa-typescript
  • aws-nodejs-ecma-script
  • aws-python
  • aws-python3
  • aws-ruby
  • aws-provided
  • aws-kotlin-jvm-maven
  • aws-kotlin-jvm-gradle
  • aws-kotlin-nodejs-gradle
  • aws-groovy-gradle
  • aws-java-maven
  • aws-java-gradle
  • aws-scala-sbt
  • aws-csharp
  • aws-fsharp
  • aws-go
  • aws-go-dep
  • aws-go-mod
  • plugin

Create your first boilerplate .

sls create --template aws-python --path ~/demoproject
cd ~/demoproject

Note : sls is short alias for serverless. You can also use

serverless create --template aws-python --path ~/demoproject

There will be two file created when you run the following command.

  1. handler.py : This is the file where all you lambda code consist.
  2. serverless.yml: All the services that are required to invoke the lambda are a part of the serverless.yml file.

Let us quickly create a simple hello world program using serverless Function.

handler.py

def hello(event, context):
return "Hello-World"

Voila this is enough to create a simple lambda that will return Hello-World on invocation. To simply deploy the lambda and check if it is invoking via cli and printing some output or not

sls deploy -v

will produce some output like this

Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service serverless-project2.zip file to S3 (2.35 KB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...

Invoking A Function:

To invoke a function via CLI you can type the following command and check that the lambda has been invoked and will result the desired output

sls invoke -f {{fucntion-name}} -l # -l is for the logssls invoke -f hello -l

If you guys have done thing right by now you will be getting some output like this

"hello World"
--------------------------------------------------------------------
START RequestId: 47c31498-f270-41c5-bb17-88c09079f26e Version: $LATEST
END RequestId: 47c31498-f270-41c5-bb17-88c09079f26e
REPORT RequestId: 47c31498-f270-41c5-bb17-88c09079f26e Duration: 0.25 ms Billed Duration: 100 ms Memory Size: 1024 MB Max Memory Used: 35 MB Init Duration: 0.79 ms

NOTE: Above we use “ sls deploy -v ” to deploy the complete stack we can deploy a single function using the same command by passing on the function name like this: “ sls deploy -f hello -v “

Creating A simple Hello World API

To create a simple hello world API you need to invoke your lambda via api-gateway. The intergration manually is much more complex than using the simple way provided by the serverless-framework

Now it’s the time to play with serverless.yml file

service: yashshahprovider:
name: aws
runtime: python3.6
versionFunctions: False #This is to disallow lambda to create multiple versions as lambda has limit for code size
memorySize: 128 #memory allocated to the lambda
region: us-west-2
profile: default #profile name that you have created to access the aws
functions:
hello:
handler: handler.hello #name of the function
events:
- http: # Mean you require http endpoint
path: hello # the path on which you require the response
method: get # The method

Make some changes to add statusCode to to the lambda handler in handlers.py

def hello(event, context):
print("Hi")
return dict(
statusCode=200
body="Hello"
)

At last Deploy the complete project using the following command

sls deploy --stage dev -v

You will get a stack output like this

After Successfully Deploying the API you will get a endpoint in the output of the serverless function from which you can access the hello-world API you have created.

Adding Environment Variable

An environment variable is a variable whose value is set outside the program, typically through functionality built into the operating system or microservice. An environment variable is made up of a name/value pair, and any number may be created and available for reference at a point in time.

serverless.yml

service: yashshahprovider:
name: aws
runtime: python2.7
profile: private
region: us-east-1
memorySize: 128
timeout: 6
functions:
hello:
handler: handler.hello
environment: # Added an environment variable [name]
name: "Yash Shah"

handler.py

import osdef hello(event, context):
return os.environ["name"]

Adding Iam Roles To The Lambda Function

I am roles will be attached to the lambda function and will provide access to the lambda function during invocation to access aws services.

Let me demo with a short code where lambda will access all the lambda function in a particular account.

serverless.yml

service: yashshahprovider:
name: aws
runtime: python2.7
profile: private
region: us-east-1
memorySize: 128
timeout: 6
iamRoleStatements:
- Effect: "Allow"
Action:
- "lambda:*"
Resource:
- "*"
functions:
hello:
handler: handler.hello
environment:
name: "Yash Shah"

handler.py

import boto3def hello(event, context):
client=boto3.client("lambda")
response=client.list_functions()
return response

Adding You Lambda Function Inside VPC

serverless.yml

Adding A Lambda inside VPC will help you to make your lambda private and allow lambda to access all the private resources like RDS, Redis and elasticsearch. When Lambda is invoked inside a vpc it will take an IP from the subnet allocated to the lambda function. Make sure to allocate the subnet with sufficient amount of IPs or address a complete seperate subnet for lambda invocation only.

Lambda VPC configuration can be done at both the level provider level as well as the function level.

service: yashshahprovider:
name: aws
runtime: python2.7
profile: private
region: us-east-1
memorySize: 128
timeout: 6
iamRoleStatements:
- Effect: "Allow"
Action:
- "lambda:*"
Resource:
- "*"
functions:
hello:
handler: handler.hello
environment:
name: "Yash Shah"
vpc:
securityGroupIds:
- sg-xxxxxxx
- sg-xxxxxxx
subnetIds
- subnet-xxxxx
- subnet-xxxxx

handler.py

import boto3def hello(event, context):
client=boto3.client("lambda")
response=client.list_functions()
return response

After Adding the vpc section in the serverless yaml file. You can deploy the serverless stack and check for the changes in the console itself.

Conclusion

At the end all i want to say is that the serverless framework is one of the most common framework for api-deployment and is widely used across many organization. You have the option to go for the language you are comfortable with.

--

--