Request sending json

Asked

Viewed 596 times

-1

I’m trying to make a request for the python. Follow what I’ve tried:

    url = 'http://localhost:8080/detection/'
    headers = {'charset': 'utf-8'}
    response = requests.post(url, json=data, headers=headers)
    print(response.status_code)

I have already checked several times, what comes by the date, is correct. I tried to call the route by Postman too, and it goes perfectly. I was able to copy and paste the json I sent, and it is correct. However, when I call the route by python, it returns error 400

  • 3

    Put up an example of how you’re riding that data in python before sending please

1 answer

0

There is a difference between using the parameter json and the parameter data, maybe you’re confusing the two.

In a POST request, the headers and the "body" of the message are sent. In the case of the use of json or data, the body is nothing more than a string; it turns out that it is a string sent in a different format to one or the other.

In the case of the parameter data, is sent as a form (as if it were your browser after clicking "send") and a header indicating that the body content is of the format x-www-form-urlencoded is automatically added:

In [9]: r = requests.post('https://httpbin.org/anything', data={'foo': 'bar', 'baz': 1337})

In [10]: r.request.body
Out[10]: 'foo=bar&baz=1337'

In [11]: r.request.headers['Content-Type']
Out[11]: 'application/x-www-form-urlencoded'

When you use the parameter json, the requests automatically transforms your body into JSON and adds a header indicating that the body content is of the type JSON:

In [13]: r = requests.post('https://httpbin.org/anything', json={'foo': 'bar', 'baz': 1337})

In [14]: r.request.body
Out[14]: b'{"foo": "bar", "baz": 1337}'

In [15]: r.request.headers['Content-Type']
Out[15]: 'application/json'

Which of the two you will use will depend on the format the API accepts, but bear these differences in mind.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.