Python - API 2.0 Zenvia - urllib.error.HTTPError: HTTP Error 400: Bad Request

0

The software below has the following intent: extract data from an excel .XLS file and send SMS with information extracted through the Zenvia platform.

Here is the Zenvia Platform 2.0 API link: link

import re
import urllib.request
import xlrd
import configparser

config = configparser.ConfigParser()
config.read('config.txt')
authorization = config.get('configuration', 'authorization')


wb = xlrd.open_workbook('exemplo.xls', encoding_override="cp1252", ragged_rows=True) # enconding_override remove o erro de ausência de condificação em XLS antigos.
worksheet = wb.sheet_by_index(0)
n = 1
while worksheet.cell(n,0).value != xlrd.empty_cell.value: # You can detect an empty cell by using empty_cell in xlrd.empty_cell.value
    # Captura o nome completo da paciente na planilha.
    nomecompleto = worksheet.cell(n, 0).value
    # Expressão Regular para isolar o primeiro nome. Utilizar nome.group(0) para eliminar <_sre.SRE_Match object at
    nome = re.search(r'([A-Z]*)\s', nomecompleto)
    celular = worksheet.cell(n, 2).value
    celularfloat = str(celular)
    celular = re.search(r'([0-9]*)', celularfloat)
    celularbr = '55' + celular.group(0)
    msg = ('Senhora ' + nome.group(0) + 'a CLIMAE confirma sua consulta com o(a) médico(a) ' + worksheet.cell(n,3).value + ' no dia ' + worksheet.cell(n,4).value + '. Responda gratis S para confirmar ou N para cancelar.' + ';' + 'CLIMAE')
    print (celular.group(0) + ';' + 'Senhor(a) ' + nome.group(0) + 'a CLIMAE confirma sua consulta com o(a) médico(a) ' + worksheet.cell(n,3).value + ' no dia ' + worksheet.cell(n,4).value + '. Responda gratis S para confirmar ou N para cancelar. CLIMAE')
    values = """
    {
        "sendSmsRequest": {
        "from" : "CLIMAE",
        "to":  "%s",
        "schedule": "NONE",
        "msg": "%s",
        "callBackOption": "NONE",
        "id": "002",
        "aggregateId": "1111"
        }
    }""" % (celularbr, msg)
    headers = {
        "Content-Type": "application/json",
        "Authorization": authorization,
        "Accept": "application/json"
    }
    values = values.encode('utf-8')
    request = urllib.request.Request("https://api-rest.zenvia360.com.br/services/send-sms", data=values, headers=headers)
    response_body = urllib.request.urlopen(request).read()
    n = n + 1
    if n >= worksheet.nrows:
        break

The software has returned the following error message:

Traceback (most recent call last):
  File "C:/Users/tocvi/Dropbox/Python/Pysms/readexcel.py", line 50, in <module>
    response_body = urllib.request.urlopen(request).read()
  File "C:\Anaconda3\lib\urllib\request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Anaconda3\lib\urllib\request.py", line 472, in open
    response = meth(req, response)
  File "C:\Anaconda3\lib\urllib\request.py", line 582, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Anaconda3\lib\urllib\request.py", line 510, in error
    return self._call_chain(*args)
  File "C:\Anaconda3\lib\urllib\request.py", line 444, in _call_chain
    result = func(*args)
  File "C:\Anaconda3\lib\urllib\request.py", line 590, in http_error_default
    **raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request**
    
asked by anonymous 19.07.2016 / 21:12

1 answer

1

I've never used the Zenvia API, but for what I read in the documentation, the request should be made via get or post:

import requests
url = 'https://api-rest.zenvia360.com.br/services/send-sms'
session_requests = requests.session()

result = session_requests.post(
    url, 
    data = values,
    headers = dict(referer = url)
)

Hope it helps

    
19.07.2016 / 21:57