Python Example

Created on September 17, 2024

python
sync

Import to edit/run function

This is an example function that calls an API to retrieve the current weather for a passed in city.

  • You can import and run/modify this function using the Import button at the top of this page.
  • Make sure to set the YOUR_OPENWEATHERMAP_API_KEY environment variable with a valid value
  • To run the function you need to do a POST request to the RUN url, with something like this:
{
  "city": "London"
}

Function Code

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
    }

Run Function

Input JSON

Loading...

Output