Let’s enliven the Lambda function we wrote in Part 1. Presently, it returns a fixed data to the caller. Let’s change it to fetch live weather data using OpenWeatherMap’s API service.

Getting Setup with OpenWeatherMap

If you haven’t already, you need to create a free account with OpenWeatherMap. Once you’re in, make your way to the API docs for their current weather service. The first endpoint listed is for current weather data by city name. The endpoint looks like this:

api.openweathermap.org/data/2.5/weather?q={city name},{country code}

So, for Venice, Italy…

api.openweathermap.org/data/2.5/weather?q=venice,it

We need an APPID before we can try out the endpoint. Go here to grab your key.

Notice we’re importing and using an external module, node-fetch. We could have used node’s http object, but I want to demonstrate how simple it is to deploy Lambda functions with external dependencies with Serverless.

Production Ready

We could now deploy our Lambda, but I’m feeling uncomfortable having our API key (APPID) stored within our function. This piece of configuration data is sensitive and is likely to vary between deployments and environments. It would be better if we stored the value in our app’s environment. Environment variables allow us to dynamically pass properties to our code without having to change our code.

AWS Lambda supports environment variables. Let’s see how we can set them with Serverless.

We’ve moved our APPID out of our function and dropped it into serverless.yml. Having a static value removes the dynamic nature of environment variables. We’re not able to change the value between deployments and environments without changing our configuration file.

Let’s try something else…

Serverless allows us to reference CLI options in our template, so how about passing APPID from the CLI at the point of deployment?

We now have multiple values of APPID in our env.yml file. But in serverless.yml we’ve fixed it so that we only access the dev version of the variable. We want to change the staging environment at deployment and have that reflected in our serverless.yml file.

Serverless allows us to combine reference properties in a single expression.

The syntax for retrieving the staging environment from a CLI option is ${opt:stage}. We can return a default value if stage isn’t passed, ${opt:stage, 'dev'}. Let’s combine this with the ${file(./file.yml)}** syntax: