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()