How to pass bearer token in API call using python request module? Below I have tried:
import requests
import json
api_url = " "# url
todo = "" #Data to send
headers = {"Content-Type":"application/json"} # how to pass bearer token
response = requests.post(api_url, data=json.dumps(todo), headers=headers)
print(response.json())
Define token before and change headers to:
headers = {"Content-Type":"application/json", "Authorization": f"Bearer {token}"}
Related
This is a python script to make a post call with respective header and body, but I am getting error Full authentication is required to access this resource
import requests
from requests.auth import HTTPBasicAuth
url = 'https://localhost:8000/bucket/items'
body = {
"serialNumbers": [
"AASD-ASD"
]
}
bearer_token = "07eb4900-016f-4523-a9b7-e5d6a87a7f8e"
jwt_token = "jhbasdfiunnX.faf-"
headers = {'content-type': 'application/json',
"authentication":"bearer "+ '07eb4900-a9b7-e5d6a87a7f8e',
"cookie":"jwt="+jwt_token}
headers = {"Cookie":"JWT="+jwt_token, "Authentication":"Bearer "+bearer_token, "Content-Type": "application/json" }
response = requests.post(url, body, auth=HTTPBasicAuth("abcd", "password"),headers=headers).json()
print(response)
I've been trying to post a payload to an endpoint, the endpoint requires bearer token.
using the python requests, I'm trying to post the bearer token in the header as
from requests import Session
http= Session()
accessToken = getToken(url=uri,data=payload)
authorization_header_string = 'bearer ' + accessToken
requestHeaders = {"Content-type": "text/plain", "Authorization":authorization_header_string}
headerData={"content-type":"text/plain","authorization":requestHeaders}
resp= http.post(url=uri,data=payload,headers=headerData)
but all I get is 401 error, while if I use the same token in postman it works fine.
I'm using requestbin to check wherein the authorization shows up only sometimes in the header.
Try the following:
token = "your token"
headerData={"content-type": "text/plain", "authorization": "Bearer " + token}
So i'm writing a program that post's data to a url and get's the response. In postman it requires a token. So when I tried to make it in python it's giving me a response [401].
The problem I have is trying to get the token first and then passing it to my post_data method.
I'm going to put *** by the URL and username and password for privacy concerns.
import requests
import json
import pprint
import urllib
def get_token():
tokenurl='***'
data={
'grant_type':'password',
'username':'***',
'password':'***'
}
token=requests.post(tokenurl,data=data)
print(token)
get_token()
def post_data():
url1='***'
data={"***"
}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}
response = requests.post(url, data=data_json, headers=headers)
pprint.pprint(response.json())
In the post_data() function, you can add your generated token to the headers
headers = {'Content-type': 'application/json','Authorization': 'token ***'}
*** is your generated token
i am trying to call my jwt authenticated django api that lives on an EC2 instance from my home laptop. the API will return me a auth key but when i try to use the auth key it tells me im not authorized. I have provided an example of the various methods i have tried to use to get this to work.
is there anything specifically i am doing wrong in this code that would warrant my code to consistently return 401 error? when asking for an authenticated API with a JWT token is there anything specifically i need to do or a specific way i need to set my headers so that i can get a value to return? or does this look like an issue with the backend?
import requests
from urllib2 import Request, urlopen
import jwt
from requests_jwt import JWTAuth, payload_method
import json
def tryme(chats, payload, jwt):
#method1
res = requests.post(chats, json=payload)
print res.status_code
# error 401
# method2
req = requests.get(chats, params=payload)
print req.status_code
# error 401
# method3
req = Request(chats)
req.add_header('Authorization', 'Token token={}'.format(auth['token']))
req.add_header('content-type', 'application/json')
res = urlopen(req)
print res.status_code
# error 401
#method4
token = JWTAuth(jwt['token'])
out = requests.get(chats, auth=token)
print out.status_code
# error 401
out = requests.post(chats, auth=token)
print out.status_code
# error 401
def main():
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
auth = json.loads(requests.post(api_auth, json=payload).content)
# returns auth token
payload = {'Authorization': 'Token {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'Bearer {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'JWT {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
if __name__ == '__main__':
main()
this was solved. however i upgraded to python3.
import requests
import urllib3
urllib3.disable_warnings()
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# in python3 use urllib3.
http = urllib3.PoolManager()
res = http.request('GET', chats, headers=payload)
print(res.data)
in python2:
import requests
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# make sure you are using the right request (GET vs POST)
out = requests.get(chats, headers=token)
print out.content
I have tried this to update my access token
import urllib
endpoint='https://accounts.google.com/o/oauth2/token'
data={'client_id':'25********15-6*********************7f.apps.googleusercontent.com','client_secret':'4********Pj-K*****x4aM','refresh_token':'1/tP************************O_XclU','grant_type':'refresh_token'}
encodedData=urllib.urlencode(data)
from httplib2 import Http
h = Http()
resp, content = h.request(endpoint, "POST", encodedData)
But got the error message
'{\n "error" : "invalid_request",\n "error_description" : "Required parameter is missing: grant_type"\n}'
You should specify the headers in your request like this:
resp, content = h.request(uri=endpoint,
method="POST",
body=encodedData,
headers={'Content-type': 'application/x-www-form-urlencoded'})
old-refresh_token is the refresh token you have
CLIENT_ID,CLIENT_SECRET are the credentials you can find those in google developers console
http = httplib2.Http()
TOKEN_URL = "https://accounts.google.com/o/oauth2/token"
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
parameters = urllib.urlencode({'refresh_token': old-refresh_token, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type': 'refresh_token'})
resp, response_token = http.request(TOKEN_URL, method='POST', body=parameters, headers=headers)
token_data = json.loads(response_token)
access_token = token_data['access_token']
the variable access_token now holds your access token
try it out