Python - consume loop api for paging

Asked

Viewed 171 times

0

Currently I consume data from a paginated api using python. I put a number of pages x, the problem is when there are more pages, or when there are fewer pages and you keep looping unnecessarily. Whenever the api has a next page, it returns the following information:

"has_next":true

and when you don’t have

"has_next":false.

It would be possible for me to loop by looking if there is true information, advance to new page, if return false it ends the loop ?

subd = 6
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
if subd >= 2:
    for page in a:
        request = curl.curlEc(subd, page)

follows the return stretch in Json

[
   {
      "resultados":{
         "has_next":true,
         "current_page":1,
         "pedidos":[
            {
               "id":8809,
               "user":{
                  "id":2361,
                  "name":"",
                  "cpf":"",
                  "cnpj":"",
                  "sexo":"feminino",
                  "data_nascimento":" ",
                  "devices":[
                     
                  ]
               },
               "loja":"",
               "tipo_frete":null,
               "endereco_entrega":null,
               "forma_pagamento_entrega":"Débito",
               "cupom_desconto":null,
               
  • seems a problem to be solved with the Try statement. See documentation: https://docs.python.org/3/reference/compound_stmts.html#Try

1 answer

1


Using requests would be something like:

import requests

page = 1

while True:
    # supondo que a chamada passe a página como parâmetro
    r = requests.get(f'https://dominio?page={page}')

    # testando resposta, se for diferente de 200 (OK), sai do loop
    if r.status_code != 200:
        break

    #assumindo que é uma lista com um único item
    results = r.json()[0]

    #
    # AQUI VC PROCESSA O RESULTADO
    #

    # apenas para ficar claro
    has_next = results["resultados"]["has_next"]
    
    page = page + 1

    if not has_next:
        break

Browser other questions tagged

You are not signed in. Login or sign up in order to post.