I develop a simple API request. Here is the code:
import requests
import json
#Get data
result = requests.get("https://pkip.riga.lv/documentregistration/divisionregister?district_id=516&division_id=2863")
divisions = json.loads(result.content)
info_list = []
for info in divisions:
info_list.append(info["valid_from"])
print (info_list)
div_list = list(dict.fromkeys(info_list))
#Sort
div_list.sort()
#Print
for info in div_list:
print(info)
The actual problem is, that I can not get any response. It gives an error message:
info_list.append(info["valid_from"])
TypeError: string indices must be integers
I have checked the request link syntax and it is correct. Here you can see the translated documentation, because it was not in English:
Data on institutions, their identification, hierarchy of institutions, periods of activity of institutions and specifics of document numbering.
Data fields:
number – Serial number of the record in the dataset
district_id – Municipality
request_date_time – Date and time of retrieval
division_id – Institution identifier
division_title – Name of the institution
managing_division_id – Managing authority identifier
managing_division_title – Name of the managing authority
is_managing_unit – Flag indicating that the institution is the managing
use_own_document_numbers – Indication that institutions use their own document numbering
number_prefix – The designation used in the institution’s document registration number
valid_from – The date on which the institution started
valid_to – The date on which the institution ceases to exist
updated – Date and time of the last correction
2
Answers
I copied your code to look what went wrong when transforming your data from the API request, the thing that you are doing is you want to get "valid_from" from your request but the field "valid_from" is under
so instead of trying to get valid from from districts itself you need to go to the right path of the field in json
i updated your for loop, it might still not be perfect but it should fix your problem
I hope this fixes your problem!
First of all: You can open URLs like yours in a browser (I use Firefox, but Chrome should have a usable JSON view, too) to have a decent JSON viewer to inspect the response with.
Also consider looking into ipython or jupyther. Either will enable you to run your steps interactively, and investigate the values you’re working with as you are modifying them.
When you play around with this you will notice that the
divisions
-field is another array you will have to iterate over to get thevalid_from
-values from. That can look something like this:Lastly, your last operation sorting the values in your
info_list
can be done immediately on that list. Yourdict.fromkeys
-step is effectively not doing much. Consider droppingdiv_list
entirely and sorting and displayinginfo_list
instead.