When I wrote my last article, A quick, cheap and serverless website…..S3/CloudFront/Route53, someone asked me that even though I am paying $2 a month, that money is still money and if the website isn’t used, you will still pay! Which is true as AWS charges you for data stored in S3 bucket. To go a really micro-service based website which can do some dynamic things (think calculations, getting data from DynamoDB or whatever a python program can do), I planned for a Lambda based website, which is triggered by a API gateway. There is no cost until a GET request is sent to the API gateway. If there is no traffic, you don’t really pay.
So here is my lambda function:
#! /usr/bin/python from chalice import Chalice import datetime import random, string app = Chalice(app_name='webapp') def random_world(length=10): current_time = datetime.datetime.now().time() current_time = str(current_time) content = "\nYou queried this at: %s UTC" %current_time length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' rnd = random.SystemRandom() password = "\nYour random password is:"+''.join(rnd.choice(chars) for i in range(length)) footer = "\r\r\r\r\t\t\t\tDelivered via Lambda Function; triggered by API Gateway\n" return (password+content+footer)
I used chalice to deploy it. Its actually my new friend in AWS space! 😀
$ chalice new-project app # cd app ~/webapp/app$ chalice deploy Enter MFA code: Regen deployment package. Updating IAM policy for role: app-dev Updating lambda function: app-dev API Gateway rest API already found: 3ojsan8vs5 Deploying to API Gateway stage: api https://3ojsan8vs5.execute-api.ap-southeast-2.amazonaws.com/api/
Note the API Endpoint:
And it’s there, up and serving in less than 10 seconds…
anshu@anshu-XPS:~$ curl https://3ojsan8vs5.execute-api.ap-southeast-2.amazonaws.com/api/ Your random password is:7*Car@Y@cH!jM You queried this at: 04:05:57.90Delivered via Lambda Function; triggered by API Gateway Run2: anshu@anshu-XPS:~$ curl https://3ojsan8vs5.execute-api.ap-southeast-2.amazonaws.com/api/ Your random password is:$exd2IRJ9)cXs You queried this at: 04:05:59.91Delivered via Lambda Function; triggered by API Gateway
What It did:
- Generated a random password every time a GET request is sent.
- Printed the time at which you sent the GET request.
If you like GUI, from Browser (of course, you can use Textile or Flask and make it even more to look like a WebPage):
Cost per hit is:
- Lambda: First 1 million requests per month are free
- API Gateway: The Amazon API Gateway free tier includes one million API calls received per month for up to 12 month.