Starting my Python journey with a Serverless application

Hirudinee Liyanage
7 min readJul 24, 2019

--

Photo by Christopher Rusev on Unsplash

I have never written a single line of code in Python. But I managed to write my AWS lambda function in Python, and deploy my AWS serverless application in no time!!

To follow the rest of the blog:

You should have:

  • AWS account keys (You can create one here)
  • GitHub or BitBucket account (You can create a free account. GitHub or BitBucket)
  • Sigma IDE account (The coolest web-based IDE for serverless application development. Create one here; it’s totally free!)
    and…
  • zero Python knowledge

You should know:

  • your way around AWS serverless development.

Background

About a month ago, I started my work on Sigma after a year-long break. Sigma IDE — as I knew it — has changed a lot. From new resources and triggers to a cool new dashboard, SLAppForge team has done some awesome upgrades to it. Support for Python was one of those major upgrades, and I was so excited to try it out.

Well, there was one issue though, I have never tried Python before!!! Python has had a significantly high growth during the last decade compared to other mainstream programming languages. Python covers a large area of application domains from simple web development to scientific and numeric computing. So what better time for me to dive into the world of Python than now!!

Creating my first Python lambda function

If you have the tiniest interest in serverless application development, Sigma IDE is something you should try out today. Lucky for me, I already have an account in Sigma IDE (you can create one ) and I have logged in to the IDE.

This is your Sigma editor’s view on the startup.

The default Sigma project creates a lambda function file in NodeJS. But for this blog, we want the function file in Python. So I navigated to Project tab on the left-hand side, clicked on the plus icon next to the project folder and clicked New Python Function File.

I gave a name to my function ( MyfirstPython ) , then had to select a Python version for my function.

Why two different versions of Python??

Before even creating my Python function file, I ran into my first question. Remember, this is me taking a deep dive into Python with zero prior knowledge. So I just googled “Python 2.7 and 3.6” and read some interesting articles (like Python2orPython3 and Python 2 vs Python 3 )

Python 2.x is legacy, Python 3.x is the present and future of the language

wiki.Python.org

I decided to go with Python 3.6. But there may be scenarios where the user needs to create Python functions in 2.7. If so, the user can easily select version 2.7 instead of 3.6.

Wait, what is __int__.py?

Okay, now I have created my function file, and it is under the project folder. But wait a minute, there is another Python file, __int__.py. What is that!!!

I did not add anything like that!!

So again, here comes the google search. As usual, Stack Overflow for the rescue! According to this answer it used to be a required part of a regular package, but newer namespaced packages don’t need it anymore. So I kept the __int__.py file as it is, and moved on to the important Python file, MyfirstPython.py.

What’s on the Python function file

Python function file is created with the following initial code snippet.

def handler(event, context):
return {"message": "Successfully executed"}

I read AWS documents for the lambda function handler in Python. Since I already have the above code snippet, I quickly edited it, so when the lambda is called, it returns and from the event as a message.

def handler(event, context):
message = 'Hello {} {}!'.format(event['first_name'],
event['last_name'])
return {
'message' : message
}

My first Python keywords

I did a quick lookup for the two keywords that were already in the created function file. In Python, a function is defined using the def keyword. The return keyword is to exit a function and return a value (W3schools)

Creating a Lambda trigger

Now I am ready to create our serverless application. My scenario is when a user makes an API call, He gets a response with the current time.

First things first, I need to create the API trigger. Navigate to the Resources pane on the left-hand side. First resource on the AWS resource list is API Gateway. All you have to do is: drag and drop the API resource on to theevent parameter of the handler.

Let’s create a new API. Give a name to your API ( Pythontest ). Give a resource path (/test/currenttime) and select the POST method. I enabled CORS, gave Test as the deployment stage, and Inject the trigger.

That’s it. With Sigma IDE you don’t have to log in to AWS console to create the trigger or add it to the lambda function. Once you have configured the API on the IDE, the rest will be taken care of by Sigma when you deploy the project to AWS. You can click on the little icon next to the def keyword (trigger config icon) if you want to change or update the trigger you have added.

Returning the current time

I have already edited the function to return and first_name last_name from the event. I did a little change to the code so the function returns the current time when the user calls the API. Needless to say, had to take a look around the internet and below is my final handler code.

import datetime

def handler(event, context):
current_time = datetime.datetime.now().time()
message = 'Hello {} {}! The time is '.format(event['first_name'],
event['last_name'])
return {
'message' : message + str(current_time)
}

Side Note: I was not able to get my code to work the first time around. (duh, obviously!!) So I had to test the function a couple of times before I could finally get the function to return the message I wanted. Inside Sigma IDE I wrote and ran tests in just a few clicks, which saved me a lot of trouble. Sigma gives you rich Testing and Debugging functionality for your serverless application. I will come back to that in another post.

I am ready to deploy!

Well, I have created our trigger and lambda function. All left to do is deploy the function to AWS. Navigate to the toolbar and click on the Deploy Project Icon. Sigma IDE saves your Sigma project to GitHub or BitBucket, then build the project and finally deploy it to AWS.

If everything went okay, after the deployment you should get a Changes summary like the following.

Copy the output URL (You can find it at the end of Changes summary pop-up or by clicking on Project Info icon on the toolbar) and, using an HTTP client (I used the inbuilt HTTP client, inside the Sigma IDE ), send a POST request to the API endpoint. Below is the request body you should send.

{
"first_name": "Johnny",
"last_name": "Depp"
}

And I got a nice response like this, with a greeting and the time.

{ "message": "Hello Johnny Depp! The time is 07:34:30.905913" }

Final Thoughts

Yeah!! I managed to deploy a lambda written in Python and execute it successfully, without any Python knowledge. Since I now have a taste of the language, I am more excited to learn and try out Python in a proper way. Below are some of the resources/ tutorials I found useful.

https://www.python.org/about/gettingstarted/ https://developers.google.com/edu/Python/ https://www.codecademy.com/learn/learn-Python-3

Originally published at http://thesunnysidestories.wordpress.com on July 24, 2019.

--

--

Hirudinee Liyanage

A QA Engineer. Writes about lessons learned and knowledge gained.