alinaz
alinaz

Reputation: 149

How to write a python loop to change a value for a dictionary key in API request?

I am writing an API request that gives paginated results. To get results from the next page I need to take a value of 'next_page_cursor' and put it in the parameters of my request that is a dictionary.

This is what I have tried so far. Need to keep changing cursor value in params until there are no more pages.

params = {'title': 'Cybertruck',
          'per_page':100,
          'cursor': '*'
         }


response = requests.get("https://api.aylien.com/news/stories", 
                       headers = headers,   params=params).json()

if "next_page_cursor" in response:
    cursor = response["next_page_cursor"]

Upvotes: 0

Views: 564

Answers (1)

nicoring
nicoring

Reputation: 683

You can use a while loop:

params = {
    "title": "Cybertruck",
    "per_page": 100,
    "cursor": "initial_cursor"
}

def make_request(params)
    return requests.get("https://api.aylien.com/news/stories", 
                        headers=headers, params=params).json()
result = []
response = make_request(params)
while "next_page_cursor" in response:
    params["cursor"] = response["next_page_cursor"]
    response = make_request(params)
    result.append(response["information_your_are_interested_in"])

Upvotes: 1

Related Questions