CRM

wsouza
Member

Limitação na busca de todos os Negócios

SOLVE

Bom dia a todos.

Estou com o seguinte problema, preciso pesquisar por todos meus Negócios(Deals) os negocios que estão com o "status" 'dealstage': 'closedwon'. Quando faço a pesquisa me retorna no max 100 resultados, sendo que o total são 553.

Minha duvida é, como faço para buscar todo os 553 resultados? 

 

Meu código:

import json
import hubspot
# from pprint import pp, pprint
from hubspot.crm.deals import ApiException

class Deals():

    def getDeals():
        token = MY_KEY

        client = hubspot.Client.create(api_key=token)

        try:
            api_response = client.crm.deals.basic_api.get_page(limit=100, properties=["dealname,dealstage,id_do_contato_associado "], archived=False)
            print(api_response)      
        except ApiException as e:
            print("Exception when calling basic_api->get_page: %s\n" % e)

    print(getDeals())

 

Resultado(Uma parte porque sao 100):

{'paging': {'next': {'after': '3533556345',
                     'link': 'https://api.hubapi.com/crm/v3/objects/deals?archived=False&limit=3&after=3533556345&properties=dealname%2Cdealstage%2Cid_do_contato_associado+'}},


 'results': [{'archived': False,
              'archived_at': None,
              'associations': None,
              'created_at': datetime.datetime(2020, 11, 27, 19, 57, 59, 715000, tzinfo=tzutc()),
              'id': '3533438287',
              'properties': {'createdate': '2020-11-27T19:57:59.715Z',
                             'dealname': 'Daniel Freire Fiuza',
                             'dealstage': 'closedlost',
                             'hs_lastmodifieddate': '2021-09-09T10:56:59.557Z',
                             'hs_object_id': '3533438287',
                             'id_do_contato_associado': '201'},
              'updated_at': datetime.datetime(2021, 9, 9, 10, 56, 59, 557000, tzinfo=tzutc())},
             {'archived': False,
              'archived_at': None,
              'associations': None,
              'created_at': datetime.datetime(2020, 11, 27, 20, 13, 2, 938000, tzinfo=tzutc()),
              'id': '3533465504',
              'properties': {'createdate': '2020-11-27T20:13:02.938Z',
                             'dealname': 'Jonatha Silva',
                             'dealstage': 'closedlost',
                             'hs_lastmodifieddate': '2021-09-05T14:28:50.686Z',
                             'hs_object_id': '3533465504',
                             'id_do_contato_associado': '251'},
              'updated_at': datetime.datetime(2021, 9, 5, 14, 28, 50, 686000, tzinfo=tzutc())},
             {'archived': False,
              'archived_at': None,
              'associations': None,
              'created_at': datetime.datetime(2020, 11, 27, 20, 59, 48, 417000, tzinfo=tzutc()),
              'id': '3533556344',
              'properties': {'createdate': '2020-11-27T20:59:48.417Z',
                             'dealname': 'Márcio Cavalcante de Vasconcelos',
                             'dealstage': 'closedlost',
                             'hs_lastmodifieddate': '2021-09-05T05:36:02.254Z',
                             'hs_object_id': '3533556344',
                             'id_do_contato_associado': '301'},
              'updated_at': datetime.datetime(2021, 9, 5, 5, 36, 2, 254000, tzinfo=tzutc())}]}

 

0 Upvotes
1 Accepted solution
wsouza
Solution
Member

Limitação na busca de todos os Negócios

SOLVE

Felipe, obrigado por responder, mas consegui resolver meu problema. 

 

Segue a baixo o codigo de da solução se alguem mais precisar.

 

max_results = 20000
        hapikey = YOUR_KEY 
        limit = 250
        deal_list = []
        get_all_deals_url = "https://api.hubapi.com/deals/v1/deal/paged?&includeAssociations=true&properties=dealname&properties=dealstage&properties=pipeline&"
        parameter_dict = {'hapikey': hapikey, 'limit': limit}
        headers = {}

        # Paginate your request using offset
        has_more = True
        while has_more:
            parameters = urllib.parse.urlencode(parameter_dict)
            get_url = get_all_deals_url + parameters
            r = requests.get(url= get_url, headers = headers)
            response_dict = json.loads(r.text)
            has_more = response_dict['hasMore']
            deal_list.extend(response_dict['deals'])
            parameter_dict['offset']= response_dict['offset']
            if len(deal_list) >= max_results: # Exit pagination, based on whatever value you've set your max results variable to.
                print('maximum number of results exceeded')
                break

View solution in original post

0 Upvotes
4 Replies 4
PamCotton
Community Manager
Community Manager

Limitação na busca de todos os Negócios

SOLVE

Olá @wsouza tudo bem? Removi esse post do spam por conta de segurança e das informações do API que as vezes pode fornecer o api key que é algo privado, irei marcar alguns de nossos top contribuidores @FelipeFelix @DanielSanchez alguma sugestão para @wsouza ?

 

Obrigada!

Pam

Você sabia que a Comunidade está disponível em outros idiomas?
Participe de conversas regionais, alterando suas configurações de idioma !


Did you know that the Community is available in other languages?
Join regional conversations by changing your language settings !




0 Upvotes
FelipeFelix
Top Contributor

Limitação na busca de todos os Negócios

SOLVE

Oi, @wsouza! Tudo bem?

 

Pelo que vi no seu código, tem um limitador de 100 registros nele. Se você retirar esse limite, acredito que a API irá retornar todos os 553 registros.

Como há um limite de 100 registros, isso tem que ser feito por paginação - retornando 5 páginas de Deals.

 

Espero ter conseguido te ajudar!

 

@PamCotton, obrigado por me marcar. 🙂

 

Abs,
Felipe Felix

0 Upvotes
wsouza
Solution
Member

Limitação na busca de todos os Negócios

SOLVE

Felipe, obrigado por responder, mas consegui resolver meu problema. 

 

Segue a baixo o codigo de da solução se alguem mais precisar.

 

max_results = 20000
        hapikey = YOUR_KEY 
        limit = 250
        deal_list = []
        get_all_deals_url = "https://api.hubapi.com/deals/v1/deal/paged?&includeAssociations=true&properties=dealname&properties=dealstage&properties=pipeline&"
        parameter_dict = {'hapikey': hapikey, 'limit': limit}
        headers = {}

        # Paginate your request using offset
        has_more = True
        while has_more:
            parameters = urllib.parse.urlencode(parameter_dict)
            get_url = get_all_deals_url + parameters
            r = requests.get(url= get_url, headers = headers)
            response_dict = json.loads(r.text)
            has_more = response_dict['hasMore']
            deal_list.extend(response_dict['deals'])
            parameter_dict['offset']= response_dict['offset']
            if len(deal_list) >= max_results: # Exit pagination, based on whatever value you've set your max results variable to.
                print('maximum number of results exceeded')
                break
0 Upvotes
wsouza
Member

Limitação na busca de todos os Negócios

SOLVE

Muito Obrigado Pam, 

 

estou com urgência nessa demanda porque não sei mais como fazer.

0 Upvotes