0

I want to do a post request in python with basic authentication AND token. I have already tested the post in postman and it worked but with python I always get status code 403.

For this API I have to do...

  • first fetch a token from the header with a GET request
  • use this token in header for POST request
auth = HTTPBasicAuth('User', 'Password')

token = requests.get(URL_token, auth=auth, headers={"x-csrf-token":"FETCH"}).headers['x-csrf-token']

requests.post(POST_url, data=json.dumps(test_data), headers={"x-csrf-token":token}, auth=auth)

The test_data are type of a list and again, in postman it works.

Is there something which I am doing wrong in the POST?

Christian
  • 401
  • 1
  • 5
  • 14
  • Does this answer your question? [How to POST JSON data with Python Requests?](https://stackoverflow.com/questions/9733638/how-to-post-json-data-with-python-requests) – MatBailie Jul 10 '23 at 07:57

2 Answers2

0

In Postman, your JSON payload as the body, but you're passing it data which is used for form data.

Therefore, try changing this line

requests.post(POST_url, data=json.dumps(test_data), headers={"x-csrf-token":token}, auth=auth)

to

requests.post(POST_url, json=test_data, headers={"x-csrf-token":token}, auth=auth)
Zero
  • 1,807
  • 1
  • 6
  • 17
0

You have to do every step within a requests.Session():

s = requests.Session()
token = s.get(get_test_token, auth=auth, headers={"x-csrf-token":"FETCH"}).headers['x-csrf-token']
s.post(get_test_token, json=test_data, headers={"x-csrf-token":token}, auth=auth)
Christian
  • 401
  • 1
  • 5
  • 14