0

This is my postman call for the API and I am getting the needed response successfully.

P.S.: I have added the header: 'Content-Type': 'application/json'

Here's the CURL generated by Postman:

curl --location 'api.example.com/apis/v2/show_user_reports' \ --header 'Content-Type: application/json' \ --form 'token="XXXXXXXXXXXXXXXXXXXXXX"' \ --form 'client_id="61"' \ --form 'user_id="7801"'

enter image description here

Now I am making an this API call using python 3.6 with same parameters and headers but it doesn't work:

url = 'https://api.example.com/apis/v2/show_user_reports'
headers = {'Content-Type': 'application/json'}
data = {'token': 'XXXXXXXXXXXXXXXXXXXXXX', 'client_id': '61', 'user_id': '7801'}

requests.post(url=url, data=json.dumps(data), headers=headers).json()

By doing this, I am getting this response:

{'error': 'Please Provide Client Id'}

Sure I am missing some small thing in this but couldn't find what.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Harshit verma
  • 506
  • 3
  • 25

1 Answers1

1

EDITED (previous answer was not correct)

Your curl is posting using --form, placing each parameter as an attachment. This is done by using files parameter in requests.post:

url = 'https://api.example.com/apis/v2/show_user_reports'
headers = {'Content-Type': 'application/json'}
files = {
    'token': (None, '"XXXXXXXXXXXXXXXXXXXXXX"'),
    'client_id': (None, '"61"'),
    'user_id': (None, '"7801"'),
}
requests.post(url=url, files=files, headers=headers)

Docs for multipart POST

The parameter attachments do not need a filename, so None is specified.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Already tried this, getting the same error "{'error': 'Please Provide Client Id'}" – Harshit verma Jun 22 '23 at 06:15
  • Sorry, I missed a thing. I hope this should be correct now. – Amadan Jun 22 '23 at 06:32
  • Sorry man, getting the same error again – Harshit verma Jun 22 '23 at 06:52
  • Hmm, I see. The only difference is the boundary, which seems to get overwritten by adding the Content Type header, which sucks. Try if it will work without setting Content Type, which should give it the correct boundary but with `multipart/form-data`. If the server really wants `application/json`, then you will have to [construct the Content Type header and the body yourself](https://stackoverflow.com/questions/36286656/python-set-up-boundary-for-post-using-multipart-form-data-with-requests) (making sure Content Type is as you wish). – Amadan Jun 22 '23 at 19:34