CRM

TSiilva
Member

Exportando Associação

SOLVE
Olá,

Bem com um problema para utilizar o 
associationTypeId nesse codigo que faz uma exportação automatica do HS, já está tudo certo mais preciso que ele imprima também está Associação dentro do meu arquivo (xlsx)

"objectType": "TICKETS",
        "associationTypeId": 28, #help
        "objectProperties": [
            'subject',
            'hs_pipeline',      
            'hs_pipeline_stage',
            'createdate',
            'hs_lastmodifieddate',
 
 
 
0 Upvotes
1 Accepted solution
Brenner
Solution
Recognized Expert | Platinum Partner
Recognized Expert | Platinum Partner

Exportando Associação

SOLVE

Olá @TSiilva , 

 

Desculpa a demora, estava em viagem. Perguntei aqui para o meu time, e recebi esse tipo de resposta, veja se ajuda, por favor: 

 

>> To export the association label between two different objects in HubSpot using the HubSpot API, you'll need to make use of the "association label" action to retrieve the label associated with the specified association type ID. Here's how you can modify your code to achieve this:

 

```python
import requests

# Define the API endpoint and your API key
url = "https://api.hubspot.com/crm/v3/objects/tickets/export"
api_key = "YOUR_API_KEY_HERE"

# Define the association type ID
association_type_id = 28

# Define the payload for the export request
payload = {
"format": "xlsx",
"objectType": "TICKETS",
"associationTypeId": association_type_id,
"objectProperties": [
'subject',
'hs_pipeline',
'hs_pipeline_stage',
'createdate',
'hs_lastmodifieddate',
]
}

# Define headers with API key
headers = {
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
"Content-Type": "application/json"
}

# Make the export request
response = requests.post(url, headers=headers, json=payload)

# Check if the request was successful
if response.status_code == 200:
# Export request successful, retrieve the association label
association_label = response.json().get("associationLabel")
print("Association Label:", association_label)
else:
# Request failed, print error message
print("Error:", response.status_code, response.text)
```

 

In this code:

 

  • Replace `"YOUR_API_KEY_HERE"` with your actual HubSpot API key.
  • Set the `association_type_id` variable to the appropriate association type ID you want to export the label for.
  • The export request is made to the HubSpot CRM API endpoint for exporting tickets with the specified association type ID.
  • Upon a successful request (status code 200), the association label is retrieved from the response JSON and printed.
  • If the request fails, an error message with the status code and response text is printed.

This code should allow you to export the association label between two different objects in HubSpot using the specified association type ID.

 

Espero ter ajudado. 



Brenner Natal



HubSpot Consultant | Inbound Marketer



--------------------------------------------------


Se a minha resposta te ajudou, por gentileza, clique no botão: " Aceitar como solução ".
Ainda com dúvidas? Responda a minha postagem para que possamos continuar te ajudando!
Obrigado por postar na comunidade da HubSpot! .



View solution in original post

0 Upvotes
6 Replies 6
Brenner
Recognized Expert | Platinum Partner
Recognized Expert | Platinum Partner

Exportando Associação

SOLVE

Olá @TSiilva 

 

Eu infelizmente não tenho acesso rápido ao banco de dados para pegar a informação correta, mas tenta incluir "associationLabel" no code

 

Obrigado @PamCotton pela menção

 



Brenner Natal



HubSpot Consultant | Inbound Marketer



--------------------------------------------------


Se a minha resposta te ajudou, por gentileza, clique no botão: " Aceitar como solução ".
Ainda com dúvidas? Responda a minha postagem para que possamos continuar te ajudando!
Obrigado por postar na comunidade da HubSpot! .



0 Upvotes
TSiilva
Member

Exportando Associação

SOLVE

Olá @Brenner 

 

Você consegue me dar algum exemplo de como posso usar o "associationLabel", não consegui localiza-lo no developers.hubspot

 

0 Upvotes
Brenner
Solution
Recognized Expert | Platinum Partner
Recognized Expert | Platinum Partner

Exportando Associação

SOLVE

Olá @TSiilva , 

 

Desculpa a demora, estava em viagem. Perguntei aqui para o meu time, e recebi esse tipo de resposta, veja se ajuda, por favor: 

 

>> To export the association label between two different objects in HubSpot using the HubSpot API, you'll need to make use of the "association label" action to retrieve the label associated with the specified association type ID. Here's how you can modify your code to achieve this:

 

```python
import requests

# Define the API endpoint and your API key
url = "https://api.hubspot.com/crm/v3/objects/tickets/export"
api_key = "YOUR_API_KEY_HERE"

# Define the association type ID
association_type_id = 28

# Define the payload for the export request
payload = {
"format": "xlsx",
"objectType": "TICKETS",
"associationTypeId": association_type_id,
"objectProperties": [
'subject',
'hs_pipeline',
'hs_pipeline_stage',
'createdate',
'hs_lastmodifieddate',
]
}

# Define headers with API key
headers = {
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
"Content-Type": "application/json"
}

# Make the export request
response = requests.post(url, headers=headers, json=payload)

# Check if the request was successful
if response.status_code == 200:
# Export request successful, retrieve the association label
association_label = response.json().get("associationLabel")
print("Association Label:", association_label)
else:
# Request failed, print error message
print("Error:", response.status_code, response.text)
```

 

In this code:

 

  • Replace `"YOUR_API_KEY_HERE"` with your actual HubSpot API key.
  • Set the `association_type_id` variable to the appropriate association type ID you want to export the label for.
  • The export request is made to the HubSpot CRM API endpoint for exporting tickets with the specified association type ID.
  • Upon a successful request (status code 200), the association label is retrieved from the response JSON and printed.
  • If the request fails, an error message with the status code and response text is printed.

This code should allow you to export the association label between two different objects in HubSpot using the specified association type ID.

 

Espero ter ajudado. 



Brenner Natal



HubSpot Consultant | Inbound Marketer



--------------------------------------------------


Se a minha resposta te ajudou, por gentileza, clique no botão: " Aceitar como solução ".
Ainda com dúvidas? Responda a minha postagem para que possamos continuar te ajudando!
Obrigado por postar na comunidade da HubSpot! .



0 Upvotes
TSiilva
Member

Exportando Associação

SOLVE

Olá @Brenner,

Bem testei o código acima e infelizmente não funcionou, vou tentar explicar de uma melhor forma o que eu quero fazer com a API do Hub:

Bem, quero pegar a associação e imprimi-la desta maneira, como se fosse feita manualmente na hora de exportar o CRM do Hub, ela deveria ficar assim na planilha:
Ac.png

Imprimindo a coluna no Hub.

TSiilva_0-1714046671905.png


Segue abaixo o Codigo ainda em desenvolvimento:

import requests
import os
import time

association_type_id = 1


# Configurações de exportação para diferentes tipos de objetos
export_configs = [
    {
        "objectType": "#COMPANY",
        "objectProperties": [
           'hs_object_id',
            'name',
            'cnpj_string',
            'id_tba',
            'createdate',
            'hs_lastmodifieddate',
            'agencia_logbank',
            'conta_logbank',
            'status_conta_logbank',
            'preenchimento_data_conta_logbank'
        ]
    },
    {
        "objectType": "#TICKTES",
        "associationCategory": "USER_DEFINED",
        "associatedObjectType": 28,
        "objectProperties": [
            'subject',
            'hs_pipeline',      
            'hs_pipeline_stage',
            'createdate',
            'hs_lastmodifieddate',
            'solicitante',
            'cpf_ou_cnpj_do_beneficiario',
            'valor_operacao',
            'numero_de_parcelas',
            'valor_da_parcela',
            'qual_o_seu_relacionamento_com_a_tambasa_atacadistas_',
            'tempo_de_relacionamento__em_meses_'
        ]
    },
    {
        "objectType": "CONTACT",
        "associationTypeId": association_type_id,
        "objectProperties": [
            'hs_object_id',
            'firstname',
            'lastname',
            'cpf',
            'cnpj',
            'ida_tba',
            'createdate',
            'lastmodifieddate',
            'agencia_logbank',
            'conta_logbank',
            'status_conta_logbank',
            'preenchimento_data_conta_logbank',
            'email',
            "association_label"
        ]
    }
]


headers = {
    "Authorization": "XXXXXXXX",
    "Accept": "application/json",
    "Content-Type": "application/json"
}

def start_export(config😞
    data = {
        "exportType": "VIEW",
        "exportName": f"Exportação Automática de {config['objectType']}",
        "format": "xlsx",
        "language": "PT_BR",
        "objectType": config["objectType"],
        "objectProperties": config["objectProperties"],
    }
    association_label = response.json().get("associationLabel")
    print("Association Label:", association_label)
    response = requests.post(url, headers=headers, json=data)
    if response.status_code in (200, 201, 202😞
        response_data = response.json()
        export_id = response_data.get("id")
        print(f"Exportação para {config['objectType']} iniciada com sucesso. ID: {export_id}")
        return export_id
    else:
        print(f"Erro ao iniciar a exportação para {config['objectType']}: {response.status_code}, {response.text}")
        return None

def check_download(export_id, config😞
    status_url = f"https://api.hubapi.com/crm/v3/exports/export/async/tasks/{export_id}/status"
    while True:
        status_response = requests.get(status_url, headers=headers)
        if status_response.status_code in (200, 201, 202😞
            status_data = status_response.json()
            export_status = status_data.get("status")
            if export_status == "COMPLETE":
                export_url = status_data.get("result", "")
                if export_url:
                    file_response = requests.get(export_url)
                    if file_response.status_code in (200, 201, 202😞
                        directory = r"C:\Users\xxx\Desktop\Explore_hub"
                        if not os.path.exists(directory):
                            os.makedirs(directory)
                        file_path = os.path.join(directory, f"HubSpot_{config['objectType']}.xlsx")
                        with open(file_path, 'wb') as file:
                            file.write(file_response.content)
                        print(f"Arquivo baixado com sucesso e salvo em: {file_path}")
                    else:
                        print(f"Erro ao baixar o arquivo: {config['objectType']}, {file_response.status_code}")
                else:
                    print("URL de download não encontrada.")
                break
            else:
                print(f"Aguardando conclusão da exportação para {config['objectType']}. Status: {export_status}")
                time.sleep(30)
                if export_status == "CANCELED":
                    print(f"Exportação cancelada {config['objectType']}. Status: {export_status}")
                    break
        else:
            print(f"Erro ao verificar o status da exportação para {config['objectType']}: {status_response.status_code}")
            break

# Executar exportação para cada configuração
for config in export_configs:
    export_id = start_export(config)
    if export_id:
        check_download(export_id, config)



O Codigo acima inicia a exportação dos CRM's e verifica o status do mesmo, apos isso ele baixa o arquivos no diretorio desejado.

 

0 Upvotes
Brenner
Recognized Expert | Platinum Partner
Recognized Expert | Platinum Partner

Exportando Associação

SOLVE

Olá @TSiilva , desculpa a demora. 

Como ficou muito técnico, estou pedindo para um desenvolvedor me ajudar com isso, não sei se você ainda precisa dessa parte da solução, mas assim que eu conseguir o retorno dele, eu mando aqui. 



Brenner Natal



HubSpot Consultant | Inbound Marketer



--------------------------------------------------


Se a minha resposta te ajudou, por gentileza, clique no botão: " Aceitar como solução ".
Ainda com dúvidas? Responda a minha postagem para que possamos continuar te ajudando!
Obrigado por postar na comunidade da HubSpot! .



0 Upvotes
PamCotton
HubSpot Alumni
HubSpot Alumni

Exportando Associação

SOLVE

Olá @TSiilva, obrigada por postar em nossa Comunidade!

 

Gostaria de convidar nossos colaboradores, @DanielSanchez, @Brenner e @Tesore alguma recomendação para @TSiilva?

 

Obrigada,

Pam

0 Upvotes