1

I am trying (for the first time) to use APIs with Python Requests module.

I need to get some data from the API and parse it as JSON. I was able to successfully get the intended response with Postman for chrome, while testing the query.

However, when I try to execute the same code with Python the data gets encoded incorrectly. I have tried .encode('utf-8) .encode('utf-8) on my data with no success. I have read the articles on encoding in python howto (https://docs.python.org/2/howto/unicode.html) with no luck.

My code:

import requests r=requests.get("http://company.vtexcommercestable.com.br/api/oms/pvt/orders?per_page=100", headers={"Accept":"application/json","Content-Type":"application/json","X-VTEX-API-AppToken":"password","X-VTEX-API-AppKey":"testemail@gmail.com"});

data = r.json()

print r

The result:

{u'stats': {u'stats': {u'totalItems': {u'Count': 113, u'Min': 0.0, u'Max': 0.0, u'Sum': 0.0, u'Missing': 0, u'SumOfSquares': 0.0, u'StdDev': 0.0, u'Facets': {}, u'Mean': 0.0}, u'totalValue':

I would need to remove "u' .." and add keep latin characters (accents and "ñ")

Help is very much appreciated!

Tule
  • 21
  • 3

2 Answers2

1

I was able to solve the problem after installing unicodecsv package, and replacing the original csv with

import unicodecsv as csv

Then, I was able to csv.writerow Unicode characters with no problem.

Tule
  • 21
  • 3
0

Those are unicode characters - see this answer for a great explanation.

You shouldn't have any issues evaluating those as regular characters in your logic, and therefore do not need to worry about "removing them".

Community
  • 1
  • 1
David Ferris
  • 2,215
  • 6
  • 28
  • 53
  • Hi David, thank for your time, the problem is when I try to use the csv module with the writerow function, I get the following error "UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 84: ordinal not in range(128)". I believe there is some basic encoding principle I don't understand :( – Tule Jul 15 '17 at 17:17