0

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"]

4
  • You don't pass it explicitly as 'cursor': * - that's invalid, what's your initial params dict? Commented Dec 8, 2019 at 16:52
  • The initial dict is what I have in the post, the default value for 'cursor' is * which I need to swap for 'next_page_cursor" Commented Dec 8, 2019 at 16:54
  • you can't have * explicitly as value - that will raise SyntaxError: invalid syntax . Update your code Commented Dec 8, 2019 at 16:59
  • Thanks, updated. Forgot to use quote marks Commented Dec 8, 2019 at 17:33

1 Answer 1

1

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"])

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @nicoring! The resulting dictionary gives me only the values of the final page, rather than values from all pages. Do you know how to change that? Otherwise - this is very helpful, I'm much closer to what I was looking for
You have to accumulate the results somewhere. This depends on how the response looks like in this case. I will update the answer to give you some pointers how to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.