A step by step guide on how to plot climate variables using answr API
Open you preferable Python IDE or Python console and initially import the required libraries. You will notice that in order to handle the data received by answr.space API no special library is needed, just the standard "requests".
import requests # to make the API requestsimport json # to convert API response to json formatimport matplotlib.pyplot as plt # to plot the retrieved data
After importing the Python libraries, let's set all the variables that we need. For each call to the answr API you need to know the latitude and longitude coordinates of the location you are searching for and the corresponding API endpoints. Each climatic variable has it's own endpoint. Of course, authentication is needed, thus email and password are essential to retrieve any data from the API.
It's a good idea to bring all variables that you are going to use up, in order to avoid "hard coding" values later on the code
#Set the coordinates you want to have the climatic datalat ='36.2471504211426'lng ='69.104192266327'#Define the user credentialsemail ='YOUR ACCOUNT EMAIL'password ='YOUR PASSWORD'#Define the climatic variable to plotclimatic_variable_1 ='a-frost-days'#Average Frost Daysclimatic_variable_2 ='sd-frost-days'#Standard Deviation Frost Days#Define some plot parametersplot_title ='Average Frost Days with Standard Deviation'plot_xaxis ='Months'plot_yaxis ='Number of Days'
After defining the needed variables, you just need to set up your authentication process and retrieve the temporally authKey.
#Step 1: Generate a temporal API key to authentic the other API endpointsheaders ={'accept':'application/json',# Already added when you pass json= but not when you pass data=# 'Content-Type': 'application/json',}json_data ={'email': email,'password': password,}#This the variable that holds the temporally API keyauth_response = requests.post('https://api.answr.space/api:auth/auth/login', headers=headers, json=json_data)
Provided that you have provided correct credentials and haven't exceeded your monthly request limit, you will be able to proceed to the next step. Now, just call the API to get the two climatic variables that we defined above ("Average Frost Days", "Standard Deviation Frost Days").
You can always check the API reference documentation as we add additional endpoints with more data variables
#Step 2: Get the data from the answr.space APIauthkey = json.loads(auth_response.content)headers ={'accept':'application/json','Authorization':'Bearer '+authkey['authToken']+'',}params ={'Input_point':'{"type":"point","data":{"lng":'+lng+',"lat":'+lat+'}}',}response_1 = requests.get('https://api.answr.space/api:climate-variables/'+climatic_variable_1+'', params=params, headers=headers)
response_2 = requests.get('https://api.answr.space/api:climate-variables/'+climatic_variable_2+'', params=params, headers=headers)
Having the data retrieved from the API, we convert them to a json format to make plotting possible.
#Convert byte responses to json formata_frost_days = json.loads(response_1.content)s_frost_days = json.loads(response_2.content)#Rename json to key to months for better plot visualization. You can find the response keys in the API reference documentation for each endpoint
new_key = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
old_key = {"CV76_M1", "CV76_M2", "CV76_M3", "CV76_M4", "CV76_M5", "CV76_M6", "CV76_M7", "CV76_M8", "CV76_M9", "CV76_M10", "CV76_M11", "CV76_M12"}
a_frost_days =dict(zip(new_key, list(a_frost_days.values())))s_frost_days =dict(zip(new_key, list(s_frost_days.values())))
Lastly we plot the two variables in an error bar type plot with matplotlib library.
xAxis = [key for key, value in a_frost_days.items()]yAxis = [value for key, value in a_frost_days.items()]e = [value for key, value in s_frost_days.items()]plt.grid(True)## LINE GRAPH ##plt.title(plot_title)plt.errorbar(xAxis, yAxis, e, color='maroon', marker='o')plt.xlabel(plot_xaxis)plt.ylabel(plot_yaxis)
In case you want to run the entire process with a single command, bellow you can find the entire code.
import requests # to make the API requestsimport json # to convert API response to json formatimport matplotlib.pyplot as plt # to plot the retrieved data# Set the coordinates you want to have the climatic datalat ='36.2471504211426'lng ='69.104192266327'# Define the user credentialsemail ='YOUR ACCOUNT EMAIL'password ='YOUR PASSWORD'# Define the climatic variable to plotclimatic_variable_1 ='a-frost-days'# Average Frost Daysclimatic_variable_2 ='sd-frost-days'# Standard Deviation Frost Days# Define some plot parametersplot_title ='Average Frost Days with Standard Deviation'plot_xaxis ='Months'plot_yaxis ='Number of Days'# Step 1: Generate a temporal API key to authentic the other API endpointsheaders ={'accept':'application/json',# Already added when you pass json= but not when you pass data=# 'Content-Type': 'application/json',}json_data ={'email': email,'password': password,}# This the variable that holds the temporally API keyauth_response = requests.post('https://api.answr.space/api:auth/auth/login', headers=headers, json=json_data)if auth_response.status_code ==200: authkey = json.loads(auth_response.content)# Step 2: Get the data from the answr.space API headers ={'accept':'application/json','Authorization':'Bearer '+ authkey['authToken']+'',} params ={'Input_point':'{"type":"point","data":{"lng":'+ lng +',"lat":'+ lat +'}}',} response_1 = requests.get('https://api.answr.space/api:climate-variables/'+ climatic_variable_1 +'', params=params, headers=headers) response_2 = requests.get('https://api.answr.space/api:climate-variables/'+ climatic_variable_2 +'', params=params, headers=headers)# Convert byte responses to json format a_frost_days = json.loads(response_1.content) s_frost_days = json.loads(response_2.content) # Rename json to key to months for better plot visualization. You can find the response keys in the API reference documentation for each endpoint
new_key ={"January","February","March","April","May","June","July","August","September","October","November","December"} old_key ={"CV76_M1","CV76_M2","CV76_M3","CV76_M4","CV76_M5","CV76_M6","CV76_M7","CV76_M8","CV76_M9","CV76_M10","CV76_M11","CV76_M12"} a_frost_days =dict(zip(new_key, list(a_frost_days.values()))) s_frost_days =dict(zip(new_key, list(s_frost_days.values()))) xAxis = [key for key, value in a_frost_days.items()] yAxis = [value for key, value in a_frost_days.items()] e = [value for key, value in s_frost_days.items()] plt.grid(True)## LINE GRAPH ## plt.title(plot_title) plt.errorbar(xAxis, yAxis, e, color='maroon', marker='o') plt.xlabel(plot_xaxis) plt.ylabel(plot_yaxis)else:print('Return status code: '+str(auth_response.status_code))print(auth_response.content)