0

I'm a bit new to APIs and get requests and I'm using the Python requests library.

I am getting data from an API like this:

url = "https://..."
headers = {"Accept":"application/json","Content-Type":"application/json","Authorization":"..."}

response = requests.get(url=url, headers=headers)
response = response.json()

My response.json() looks like this:

[{'id': '1', 
'fruit': 'apple',
'color': 'red'},
{'id': '2', 
'fruit': 'orange',
'color': 'orange'},
{'id': '3', 
'fruit': 'banana',
'color': 'yellow'},
...]

However, I only want specific records to be returned from my get request. E.g.

I have a list desired_fruits = ['apple', 'banana] and only want the fruits that are in this list. So my response.json will look like:

[{'id': '1', 
'fruit': 'apple',
'color': 'red'},
{'id': '3', 
'fruit': 'banana',
'color': 'yellow'}]

How can I do this? Please help.

Because otherwise, I'll have to load in the whole thing and loop over the list of dictionaries to get desired records.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
mha
  • 141
  • 1
  • 11
  • If you do not want to load the whole thing (I assume it is response.json with all records), you must filter the data on the API side (using appropriate headers), send that request, and get already filtered data. If you cannot do that, you are stuck filtering your results by looping. – Vladyslav Moisieienkov Aug 03 '23 at 19:03
  • @VladyslavMoisieienkov Is there an example of where I can refer to filtering data from API side using headers? Thanks. – mha Aug 03 '23 at 19:48
  • It depends on your REST API (e.g., some weather website, etc.). You need to check the documentation. It is not related to the Python language itself. – Vladyslav Moisieienkov Aug 09 '23 at 22:35

1 Answers1

1

As you are getting back a list of dictionaries, you will essentially have to loop over them. I recommend list comprehension.

[item for item in response if item['fruit'] in desired_fruits]
Zeke Marffy
  • 188
  • 3
  • 14