KeyError: 'observations'

Hello all! When using the API I get the KeyError about observations.

Can someone help me?

KeyError                                  Traceback (most recent call last)
<ipython-input-6-246e94271d60> in <module>
     23   return pd.DataFrame({"date": dates, "gdp": values})
     24 
---> 25 brazil_df = create_gdp_dataframe(brazil_gdp_data)
     26 
     27 # Plot the GDP data using matplotlib

<ipython-input-6-246e94271d60> in create_gdp_dataframe(gdp_data)
     18 # Parse the GDP data into a pandas dataframe
     19 def create_gdp_dataframe(gdp_data):
---> 20   data = gdp_data["observations"]
     21   dates = [d["observation_date"] for d in data]
     22   values = [d["value"] for d in data]

KeyError: 'observations'

Here is my python code (using colab):

import requests
import pandas as pd
import matplotlib.pyplot as plt

# Send a GET request to the DB Nomics API to retrieve the GDP data for Brazil
def get_gdp_data(country, start_year, end_year):
  url = f"https://api.db.nomics.world/v22/series/WB/{country}/NY.GDP.MKTP.KD.ZG"
  params = {
    "observations": 1,
    "start_date": f"{start_year}-01-01",
    "end_date": f"{end_year}-12-31"
  }
  response = requests.get(url, params=params)
  return response.json()

brazil_gdp_data = get_gdp_data("BRA", 2015, 2019)

# Parse the GDP data into a pandas dataframe
def create_gdp_dataframe(gdp_data):
  data = gdp_data["observations"]
  dates = [d["observation_date"] for d in data]
  values = [d["value"] for d in data]
  return pd.DataFrame({"date": dates, "gdp": values})

brazil_df = create_gdp_dataframe(brazil_gdp_data)

# Plot the GDP data using matplotlib
plt.plot(brazil_df["date"], brazil_df["gdp"])
plt.xlabel("Year")
plt.ylabel("GDP Growth (%)")
plt.title("GDP Growth for Brazil from 2015 to 2019")
plt.show()

Look at brazil_gdp_data:

>>> brazil_gdp_data
{'_meta': {'args': {'end_date': ['2019-12-31'], 'observations': ['1'], 'start_date': ['2015-01-01']}, 'version': '22.1.9'}, 'message': "Invalid value {'observations': '1', 'start_date': '2015-01-01', 'end_date': '2019-12-31'} (dict): additional properties: ['start_date', 'end_date']"}

You want

gdp_data["_meta"]["args"]["observations"]

instead of gdp_data["observations"]

Best

Are you aware of the dbnomics Python package, a client for DBnomics API? Cf DBnomics · PyPI

Thank you @MichelJuillard

In fact, I didn’t know. Thanks.

A KeyError in Python is raised when you try to access a dictionary key that doesn’t exist in the dictionary. This error occurs when you try to access a dictionary value using a key that doesn’t exist in the dictionary. The error message typically includes the name of the key that was not found in the dictionary.

To handle this error, you can either check if the key exists in the python dictionary before trying to access it, or use the .get() method which allows you to specify a default value to return if the key does not exist in the dictionary.

my_dict = {"a": 1, "b": 2}
if "c" in my_dict:
    print(my_dict["c"])
else:
    print("Key 'c' not found in the dictionary")