1

I can access JWT secured Restful API using curl command as follows

#Get the access Token in a variable ID

export ID=`curl  -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{  "password": "admin",  "rememberMe": true,  "username": "admin"  }' 'http://localhost:8080/api/authenticate' | jq -r .id_token`

#Use this token to access endpoint 

curl 'http://localhost:8080/api/downloads' --header 'Content-Type: application/json' --header 'Accept: application/json' --header "Authorization: Bearer $ID" 

My python script for authentication part and get bearer token is as follows:

import requests

LOGIN_URL = "http://localhost:8080/api/authenticate"
ENDPOINT_URL = 'http://localhost:8080/api/downloads'
PARAMS = {'password': 'admin','rememberMe': True,  'username': 'admin'  }
r1 = requests.post(LOGIN_URL,  data =PARAMS, headers={"Content-Type": "application/json","Accept": "application/json"})
print(r1)

When i am trying to do the same through python script,Authentication request fails with message <Response [400]>

Help needed !

3
  • Please extend your error description beyond "it is not working."! Commented Jun 27, 2020 at 10:50
  • Try r1.get("id_token") instead of r1.get_dict()['id_token']. Commented Jun 27, 2020 at 11:14
  • Usually if I'm not sure about the response structure and I know it's a some sort of dictionary. I'd try sticking .__dict__ to the variable. r1.__dict__. Ps. Not supported by everything but most mainstream package classes has this implementation. Commented Jun 27, 2020 at 11:21

1 Answer 1

1

You are passing a dictionary where you should be passing JSON.

Try using json not data and pass the dictionary:

import requests

LOGIN_URL = "https://httpbin.org/post"
PARAMS = {'password': 'admin','rememberMe': True,  'username': 'admin'  }
r1 = requests.post(LOGIN_URL,  json=PARAMS, headers={"Content-Type": "application/json","Accept": "application/json"})
print(r1.text)

or pass a string and use data:

import requests

LOGIN_URL = "https://httpbin.org/post"
PARAMS = '{"password": "admin", "rememberMe": true, "username": "admin"}'
r1 = requests.post(LOGIN_URL, data=PARAMS, headers={"Content-Type": "application/json", "Accept": "application/json"})
print(r1.text)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.