ygorsm | 2024-02-09 21:43:56 UTC | #1
Good evening, could you help me?
I'm trying to import a csv contact list via API, but I'm having difficulties, I'm trying to do this via Python, the URL I found in the documentation apparently isn't working. 'https://api.sae1.pure.cloud/uploads/v2/contactlist'
Could you tell me what I'm doing wrong?
This is the code I'm using.
import base64, requests, sys, os
import pandas as pd import json import time import requests
DADOS PARA AUTENTICAÇÃO
URL = 'https://login.sae1.pure.cloud/oauth/token' clientid = '####' clientsecret = '####' credentials = f'{clientid}:{clientsecret}' encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': f'Basic {encoded_credentials}' }
requestbody = {'granttype': 'client_credentials'}
loginresponse = requests.post(URL, headers=headers, data=requestbody)
if loginresponse.statuscode == 200:
ATRELANDO O TOKEN DE ACESSO A UMA VARIAVEL
accesstoken = loginresponse.json().get('access_token')
NOVO HEADER
headersdefault = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {accesstoken}' }
name_lista = input(str("Digite o nome da lista: "))
Criando a lista de chamada
URLCREATECONTACTLIST = 'https://api.sae1.pure.cloud/api/v2/outbound/contactlists'
bodycreatecontactlist = {
"name": name_lista, "version": 1, "division": { 'id': '#####', 'name': 'Home' },
"columnNames": [ 'RA', 'CPF', 'NOME', 'FONE', 'CURSO', 'CAMPUS', 'TURNO', 'ANO', 'PERIODO', 'COMPLEMENTO', 'SUBCAMPANHA', 'TIPO_CLIENTE' ], "phoneColumns": [ { "columnName": "FONE", "type": "Comercial", } ], }
createcontactlistresponse = requests.post(URLCREATECONTACTLIST, headers=headersdefault, json=(bodycreate_contactlist))
print("Criando a Lista de contatos...\n") time.sleep(2)
if createcontactlistresponse.statuscode == 200: print(f'A Lista de contatos: {namelista} foi criada com sucesso!\n')
postcreatecontactlistjson = createcontactlistresponse.json() ContactListID = postcreatecontactlistjson.get('id')
IMPORTANDO A LISTA DE CONTATOS
URLUPLOADCONTACTLIST = f'https://api.sae1.pure.cloud/uploads/v2/contactlist' caminhoarquivocsv = 'example_path/test.csv'
arquivocsv = open(caminhoarquivocsv, 'rb') nomearquivo = os.path.basename(caminhoarquivocsv)
payload = { 'id': ContactListID, 'fileType': 'contactlist', 'contact-id-name': name_lista }
files = {'file': (nomearquivo, arquivocsv, 'csv')}
Enviar a requisição para fazer o upload do arquivo
uploadresponse = requests.post(URLUPLOADCONTACTLIST, headers=headersdefault, data=payload, files=files)
if uploadresponse.statuscode == 200: print(f'O arquivo {nomearquivo} foi importado com sucesso para a plataforma.') else: print('Ocorreu um erro ao importar o arquivo.') print(uploadresponse.text)
Fechar o arquivo CSV
arquivo_csv.close()
I am getting this error
{"message":"HTTP 404 Not Found","code":"not found","status":404,"contextId":"4aa591b4-7fac-45f8-b931-aecb8286783f","details":[],"errors":[]}
Thanks in advance.
tim.smith | 2024-02-09 22:17:00 UTC | #2
ygorsm, post:1, topic:24582
URL_UPLOAD_CONTACTLIST = f'https://api.sae1.pure.cloud/uploads/v2/contactlist'
This is the wrong hostname. See the example here: https://developer.genesys.cloud/routing/outbound/uploadcontactlists. This is an easy one to miss; API requests typically go to the Platform API host, but this one is actually using the web app UI's subdomain. In your case, the hostname would be apps.sae1.pure.cloud.
tim.smith | 2024-02-09 22:19:29 UTC | #3
ygorsm, post:1, topic:24582
the URL I found in the documentation apparently isn't working. 'https://api.sae1.pure.cloud/uploads/v2/contactlist'
Can you drop a link to the page that documents using that hostname? Or was it just a mistake when you localized the URL from page I linked? Just asking because if the wrong hostname is documented somewhere, we want to get that fixed.
ygorsm | 2024-02-14 16:05:35 UTC | #4
It was a mistake, I didn't pay attention to that part of the URL. However, after the modification, I receive a status code 400, is there something missing or wrong in the request body?
tim.smith | 2024-02-14 16:29:14 UTC | #5
Error response bodies often contain an error message indicating what's wrong with your request. What does the error body say now? What's the correlation ID from the response?
ygorsm | 2024-02-14 20:33:24 UTC | #6
Man, I tried every way I could, but the response body simply comes up empty, the only thing I can know is the 400 status that comes up. For this reason I'm thinking it might be something I must be doing wrong.
I made some modifications to my code and now it looks like this: (starting from the part that authentication has already been carried out successfully and I have already obtained a token)
name_lista = input(str("Digite o nome da lista: "))
Criando Contactlist
URLCREATECONTACTLIST = 'https://api.sae1.pure.cloud/api/v2/outbound/contactlists'
bodycreatecontactlist = {
"name": name_lista, "version": 1, "division": { 'id': 'e3b68a69-eee1-412d-bf48-b6a1cf####', 'name': 'Home' },
"columnNames": [ "RA", "CPF", "NOME", "FONE", "CURSO", "CAMPUS", "TURNO", "ANO", "PERIODO", "COMPLEMENTO", "SUBCAMPANHA", "TIPO_CLIENTE" ], "phoneColumns": [ { "columnName": "FONE", "type": "Comercial", } ], }
createcontactlistresponse = requests.post(URLCREATECONTACTLIST, headers=headersdefault, json=(bodycreate_contactlist))
print("Criando a Lista de contatos...\n") time.sleep(2)
if createcontactlistresponse.statuscode == 200: print(f'A Lista de contatos: {namelista} foi criada com sucesso!\n')
Configurações de conexão SSH
host = '10.113.2.73' port = 22 username = 'username' password = '****' arquivoremoto = '/TFTP/Genesys/testcamp.csv'
try:
Criar uma instância SSHClient
ssh = paramiko.SSHClient()
Configurar políticas de chave de host (opcional)
ssh.setmissinghostkeypolicy(paramiko.AutoAddPolicy())
Conectar ao servidor SSH
ssh.connect(hostname=host, port=port, username=username, password=password)
Abrir uma sessão SFTP
sftp = ssh.open_sftp()
with sftp.open(arquivo_remoto , 'r') as f:
Lendo o arquivo CSV com Pandas
df = pd.read_csv(f, sep=',', quotechar='"', header=0) print(df.head())
CPF = df.loc[0, 'CPF']
for index, row in df.iterrows(): CPF = row['CPF']
if pd.notna(CPF):
print(f'CPF: {CPF}')
postcreatecontactlistjson = createcontactlistresponse.json() ContactListID = postcreatecontactlistjson.get('id')
IMPORTANDO A LISTA DE CONTATOS
URLUPLOADCONTACTLIST = f'https://apps.sae1.pure.cloud/uploads/v2/contactlist' payload = { 'id': ContactListID, 'fileType': 'contactlist', 'contact-id-name': CPF }
Enviar a requisição para fazer o upload do arquivo
with sftp.open(arquivoremoto, 'rb') as f: files = {'file': (os.path.basename(arquivoremoto), f, 'csv')} uploadresponse = requests.post(URLUPLOADCONTACTLIST, headers=headersdefault, data=payload, files=files)
if uploadresponse.statuscode == 200: print(f'O arquivo {arquivo_remoto} foi importado com sucesso para a plataforma.')
else: print('Erro:', uploadresponse.statuscode) print('Erro:', uploadresponse.text) print('Erro:', uploadresponse.json())
except Exception as e: print('Erro:', str(e))
finally: if sftp: sftp.close() if ssh: ssh.close()
tim.smith | 2024-02-14 21:10:46 UTC | #7
It looks like you're probably sending the wrong headers. This request is supposed to send form data (i.e. content-type: multipart/form-data), but it looks like you're specifying content-type: application/json. That's the only thing I can see that might be wrong.
If that's not it, I'm out of ideas. The response should contain information about what's wrong with the request, but if you're not getting that info please open a case with Genesys Cloud Care to investigate further. We do not have access to the requisite information via the forum to perform that kind of investigation.
tim.smith | 2024-02-14 21:30:57 UTC | #8
ygorsm, post:6, topic:24582
the response body simply comes up empty, the only thing I can know is the 400 status that comes up
FWIW that's what I'm seeing as well when trying using cURL. A lot of the requests I've made have just resulted in the socket being closed without a response at all. Granted all of my requests were intentionally incorrect, but I can't get it give me an error message under any circumstances.
system | 2024-03-15 21:30:59 UTC | #9
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
This post was migrated from the old Developer Forum.
ref: 24582