python requests get from API and post to another API and remote u'

Heinrich Kruger heindsight at kruger.dev
Wed Aug 21 14:32:36 EDT 2019


‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Tuesday, August 20, 2019 10:18 AM, Chris Angelico <rosuav at gmail.com> wrote:

> On Tue, Aug 20, 2019 at 6:59 PM Noah noah-list at enabled.com wrote:
>
> > Hi,
> > I am trying to migrate information and data between two systems using
> > their corresponding APIs. I am using python requests.
> > I place a get request and the response from the API is "{'id': 32,
> > 'description': u'Firewall Outside', 'address': u'10.10.10.230/30'}"
> > I then take that information and attempt post it to the other API. The
> > data is not accepted and the result is an HTTP 400 code.
> > I tried posting with postman and still rejected.
> > I can post to the second API if I change the data to look like this:
> > {"id": 32, "description": "Firewall Outside", "address": "10.10.10.230/30"}
> > How can I remove all u' from the get data or from the data I am
> > attempting to post?
>
> Use Python 3. Your problems with Unicode will either disappear, or
> become a lot clearer.
>
> ChrisA
>

Yep, you should definitely aim to use Python 3. However, I looks like you are converting a dict to a string to generate your POST data, instead of properly serialising it as JSON.

Perhaps you did something like:
resp = requests.get('https://example.com/api/data')
data = resp.json()
requests.post('https://example.com/api/other_data', data=str(data))

Or maybe you did something like
print(resp.json())
and copy/pasted the result.

You will probably be better off keeping your data as a dict and using the 'json' keyword argument to 'requests.post'. For example:
resp = requests.get('https://example.com/api/data')
data = resp.json()
requests.post('https://example.com/api/other_data', json=data)

See https://2.python-requests.org/en/stable/user/quickstart/#more-complicated-post-requests for more detail.

--
Heinrich Kruger



More information about the Python-list mailing list