This is an example function that calls an API to retrieve the current weather for a passed in city.
YOUR_OPENWEATHERMAP_API_KEY
environment variable with a valid value{
"city": "London"
}
import requests
import os
YOUR_OPENWEATHERMAP_API_KEY = os.getenv('YOUR_OPENWEATHERMAP_API_KEY')
def handler(request):
try:
city = request['body']['city']
except (KeyError, TypeError):
return {
"statusCode": 400,
"body": "Please provide a 'city' in the request body"
}
if not YOUR_OPENWEATHERMAP_API_KEY:
return {
"statusCode": 400,
"body": "Please make sure to set the YOUR_OPENWEATHERMAP_API_KEY environment variable"
}
base_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"q": city,
"appid": YOUR_OPENWEATHERMAP_API_KEY,
"units": "metric"
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status() # Raises an HTTPError for bad responses
weather_data = response.json()
except requests.RequestException as e:
return {
"statusCode": 500,
"body": f"Error fetching weather data: {str(e)}"
}
temperature = weather_data['main']['temp']
description = weather_data['weather'][0]['description']
result = f"Current weather in {city}: {temperature}°C, {description}"
return {
"statusCode": 200,
"headers": {"Content-Type": "text/plain"},
"body": result
}