Search code examples
pythonapiweather-api

Not showing measures in results when using Weatherbit API


Using Python, need to display the current weather data using the website API https://www.weatherbit.io/api. Weather data should be displayed in text form. I got something like this, but it's not working as expected, as a result it shows following without measures:

#Output

 Enter city name : Paris
 Temperature (in kelvin unit) = ['temp']
 atmospheric pressure (in hPa unit) = ['pres']
 humidity (in percentage) = ['rh']
 description = ['description']

Full code:

# import required modules
import requests, json

# Enter your API key here
api_key = "API_key"

# base_url variable to store url
base_url = "https://api.weatherbit.io/v2.0/current?"
# Give city name
city_name = input("Enter city name : ")

# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name

# get method of requests module
# return response object
response = requests.get(complete_url)

# json method of response object
# convert json format data into
# python format data
x = response.json()


# store the value corresponding
# to the "temp" key of y
current_temperature = ["temp"]

# store the value corresponding
# to the "pressure" key of y
current_pressure = ["pres"]

# store the value corresponding
# to the "humidity" key of y
current_humidity = ["rh"]

# store the value of "weather"
# key in variable z
z = ["weather"]

# store the value corresponding
# to the "description" key at
# the 0th index of z
weather_description = ["description"]

# print following values
print(" Temperature (in kelvin unit) = " +
      str(current_temperature) +
      "\n atmospheric pressure (in hPa unit) = " +
      str(current_pressure) +
      "\n humidity (in percentage) = " +
      str(current_humidity) +
      "\n description = " +
      str(weather_description))

Solution

  • You forgot x in all lines.

    To make it more readable I will use name data instead of miningless x.

    data = response.json()
    
    current_temperature = data["temp"]
    current_pressure    = data["pres"]
    current_humidity    = data["rh"]
    z                   = data["weather"]
    weather_description = data["description"]
    

    BTW:

    You could use name weather instead of z to make code more readable.

    See more PEP 8 -- Style Guide for Python Code


    EDIT:

    Full code with other changes (but I don't have API_KEY to test it).

    • you don't need import json
    • you could read API_KEY from environment (or from dot file) for security
    • you don't have to create full URL but you can use get(..., params=...) for this
    • you could use f-string to make code more readable
    • code is more readable if you use print() for every line separatelly.
    import requests
    
    #import os
    #api_key = os.getenv("API_KEY")
    
    api_key = "API_KEY"
    
    city_name = input("Enter city name : ")
    
    url = "https://api.weatherbit.io/v2.0/current" # url without `?`
    
    payload = {
        'appid': api_key,
        'q': city_name,
    }   
    
    response = requests.get(url, params=payload)
    
    data = response.json()
    
    if 'error' in data:
        print('Error:', data['error'])
    else:
        temperature = data["temp"]
        pressure    = data["pres"]
        humidity    = data["rh"]
        weather     = data["weather"]
        description = data["description"]
    
        print(f"Temperature (in kelvin unit) = {temperature}")
        print(f"atmospheric pressure (in hPa unit) = {pressure}")
        print(f"humidity (in percentage) = {humidity}")
        print(f"description = {description}")
    

    EDIT:

    I checked API documentation for current weather and it uses different names in URL.

    It has to be

    payload = {
        'key': api_key,
        'city': city_name,
        #'lang': 'pl'  # for descriptions in my native language Polish
    }   
    

    And it gives temperature in data["data"][0]["temp"], pressure in data["data"][0]["pres"], etc. - so it needs

    temperature = data["data"][0]["temp"]
    pressure    = data["data"][0]["pres"]
    # etc.
    

    or you can do

    data = data['data'][0]
    
    temperature = data["temp"]
    pressure    = data["pres"]
    

    It also gives description in data["data"][0]["weather"]["description"]

    In other requests it may have more results then [0] so you may need to use for-loop

    data = data['data']
    
    for item in data:
        temperature = item["temp"]
        pressure    = item["pres"]
        print(f"Temperature (in kelvin unit) = {temperature}")
        print(f"atmospheric pressure (in hPa unit) = {pressure}")
    

    import requests
    
    #import os
    #api_key = os.getenv("API_KEY")
    
    api_key = "ef.............................."
    
    #city_name = input("Enter city name : ")
    
    city_name = 'Warsaw'
    url = "https://api.weatherbit.io/v2.0/current" # url without `?`
    
    payload = {
        'key': api_key,
        'city': city_name,
        #'lang': 'pl'  # for descriptions in my native language Polish
    }   
    
    response = requests.get(url, params=payload)
    
    data = response.json()
    
    if 'error' in data:
        print('Error:', data['error'])
    else:
        #print(data)
        
        data = data['data'][0]
        
        temperature = data["temp"]
        pressure    = data["pres"]
        humidity    = data["rh"]
        weather     = data["weather"]
        description = data["weather"]["description"]
        
        print(f"Temperature (in kelvin unit) = {temperature}")
        print(f"atmospheric pressure (in hPa unit) = {pressure}")
        print(f"humidity (in percentage) = {humidity}")
        print(f"description = {description}")