Level 1
0 / 100 XP

Get your weather with the OpenWeatherMap

In this lesson we are going to learn how to use the Open Weather API to get your local weather.

First, let's make sure you have the necessary libraries installed. You will need requests and json. You can install them using pip like this:

Text
pip install requests pip install json

Next, we need to get an API key from Open Weather. Go to their website and sign up for an account. Once you have an account, you can find your API key on the dashboard.

Now that we have our API key, we can start making requests to the API. First, let's import the necessary libraries at the top of our script:

Python
import requests import json

Next, let's create a function that will make the request to the API and return the weather data. We will pass the function our API key and our location as parameters.

Python
# Create function to make API call and return data def get_weather(api_key, zip, country): url = "https://api.openweathermap.org/data/2.5/weather" query_params = { "zip": f"{zip},{country}", # Zip, Country "appid": api_key, "units": 'imperial' # Metric, Standard or Imperial } response = requests.get(url, params=query_params) response_json = json.loads(response.text) return response_json

Now let's call our function and print out the weather data.

Python
api_key = "YOUR_API_KEY_HERE" location = "San Francisco, CA" weather_data = get_weather(api_key, location) print(weather_data)

You should see a bunch of data printed out on the screen, including the current temperature, humidity, and wind speed.

To access specific data points, you can use the get() method on the weather_data object. For example, to get the current temperature, you can use:

Python
temperature = weather_data.get('main').get('temp') print(temperature)

Try playing around with the data and see what oth…