Setting Token Header in Python Requests - python

I am calling my REST services with the following command using curl
export TOKEN= '<random>'
curl -X "GET" -H "Content-Type:application/json" -H "Authorization:Bearer ${TOKEN}" http://my-server.com
I am trying to map the same code using requests library of Python
import requests
url = 'https://httpbin.org/bearer'
headers = {'Authorization': 'Bearer', 'Content-Type':'application/json'}
r = requests.get(url, headers=headers)
print(r.status_code)
My question is, how can I set my TOKEN value in the code?

The authorization token can be added in a dict form to the headers argument as shown below:
hed = {'Authorization': 'Bearer ' + auth_token,
'Content-Type': 'application/json'}
r = requests.post(url=url, headers=hed)
I suggest reading up on this https://2.python-requests.org/en/master/user/quickstart/

Just replace your current line for this one
headers = {'Authorization': 'Bearer ' + token, 'Content-Type':'application/json'}
Depends now where you get the token from, but to include the token that's the way.

Related

Python access to API- Authentication Error

I've have been accessing an supportpal API via curl just fine using the following command. (https://docs.supportpal.com/current/REST+API)
curl.exe -i -u 'APIKEY:x' -X GET https://support.url.org/api/user/user/3697
This correctly grabs the data. I've trying replicate this with python but i continually have issues with authentication and get the following error.
Failed to authenticate because of bad credentials or an invalid authorization header
The code i'm using is straight forward.
import requests
import json
url = "https://support.url.org/api/user/user/3697"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer: {APIKEY:x}"
}
response = requests.request("GET", url, headers=headers)
print(response. Text)
I'm thinking i have an issue with the auth header, but can't figure it out.
from requests.auth import HTTPBasicAuth
import requests
url = 'https://support.url.org/api/user/user/3697'
headers = {'Accept': 'application/json'}
auth = HTTPBasicAuth('apikey', x)
req = requests.get(url, headers=headers, auth=auth)

How to access the github API via requests in python?

I am trying to access the github API via requests with python (Answers in similar questions here and here do not help).
Using curl, I am able to get a list of recent commits for a project, e.g.
curl -H "Accept: application/vnd.github.inertia-preview+json Authorization: token a0d42faabef23ab5b5462394373fc133ca107890" https://api.github.com/repos/rsapkf/42/commit
Trying to use the same setup in python with requests I tried to use
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json", "Authorization": "token a0d42faabef23ab5b5462394373fc133ca107890"}
r = requests.get(url, headers=headers)
as well as
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
my_username = "someuser"
my_token = "a0d42faabef23ab5b5462394373fc133ca107890"
r = requests.get(url, headers=headers, auth=(my_username, my_token))
but in both cases I get the response
{'documentation_url': 'https://docs.github.com/rest',
'message': 'Bad credentials'}
What am I missing here?
No Authentication is required. The following works:
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
r = requests.get(url, headers=headers)

How to generate json response from python?

I am making an API call from Python. My current code is supposed to generate a JSON response, but throws out a Response code 500 (Internal Server Error). However, when I generate the data using the API's built in extract tool, it returns the data. Code snippet is as follows:
def Performance(data):
BASEURL = 'https://api-c31.ict.com/inContactAPI/'
accessToken = (data["access_token"])
#Check if accessToken is empty or null
if accessToken!= "":
#Give necessary parameters for http request
payload={'startDate':'1/1/2020',
'endDate':'1/6/2020',
'fields':'"agentId","teamId","totalHandled"'}
#add all necessary headers
header_param = { 'User-Agent' : 'Chrome/79.0.3945.117',
'Authorization': 'bearer ' + '{accessToken}',
'content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/javascript, */*'
}
# Make get http request
response_1 = requests.get(BASEURL + 'services/{version}/agents/performance' , headers = header_param, params=payload)
#answer1.raise_for_status
#print response appropriately
print (response_1)
#response
else: print('error')
response_1 generates a Response 500. How can I generate the data from Python?
params doesn't encode your payload as JSON; json does.
response_1 = requests.get(
BASEURL + 'services/{version}/agents/performance',
headers=header_param,
json=payload)

Google Drive API POST requests?

I'm trying to interact with the Google Drive API and while their example is working, I'd like to learn how to make the POST requests in python instead of using their pre-written methods. For example, in python how would I make the post request to insert a file?
Insert a File
How do I add requests and parameters to the body?
Thanks!
UPDATE 1:
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + 'my auth token'}
datax = {'name': 'upload.xlsx', 'parents[]': ['0BymNvEruZwxmWDNKREF1cWhwczQ']}
r = requests.post('https://www.googleapis.com/upload/drive/v3/files/', headers=headers, data=json.dumps(datax))
response = json.loads(r.text)
fileID = response['id']
headers2 = {'Authorization': 'Bearer ' + 'my auth token'}
r2 = requests.patch('https://www.googleapis.com/upload/drive/v3/files/' + fileID + '?uploadType=media', headers=headers2)
To insert a file:
Create a file in Google drive and get its Id in response
Insert a file using Id
Here are the POST parameters for both operations:
URL: 'https://www.googleapis.com/drive/v3/files'
headers: 'Authorization Bearer <Token>'
Content-Type: application/json
body: {
"name": "temp",
"mimeType": "<Mime type of file>"
}
In python you can use "Requests"
import requests
import json
headers = {'Content-Type': 'application/json','Authorization': 'Bearer <Your Oauth token' }
data = {'name': 'testing', 'mimeType': 'application/vnd.google-apps.document'}
r = requests.post(url,headers=headers,data=json.dumps(data))
r.text
Above POST response will give you an id.
To insert in file use PATCH request with following parameters
url: 'https://www.googleapis.com/upload/drive/v3/files/'<ID of file created> '?uploadType=media'
headers: 'Authorization Bearer <Token>'
Content-Type: <Mime type of file created>
body: <Your text input>
I hope you can convert it in python requests.

How to make Raw REST Call for Azure using Python

I am trying to make REST Call for azure using python,
Have created Access token using ADAL in python.
But getting Error called "provided Authorization header is in invalid format."
Here is the code for that:
import adal
import requests
token_response = adal.acquire_token_with_username_password(
'https://login.windows.net/abcd.onmicrosoft.com',
'user-name',
'password'
)
access_token = token_response.get('accessToken')
url = 'https://management.azure.com/subscriptions/{subscription- id}/providers/Microsoft.Network/virtualnetworks?api-version=2015-06-15'
headers = {'Content-Type': 'application/json',
'Authorization': access_token}
response = requests.get(url=url,headers = headers)
print(response.status_code)
print(response.text)
Can anyone tell me how the access-token should look like?
And is this the correct way to generate token for REST in python?
I am reffering this link for above code:
https://msdn.microsoft.com/en-us/library/azure/mt163557.aspx
As #GauravMantri said, the format of the value of the header Authorization is Bearer <access-token> that you can refer to the section Calling ARM REST APIs of the doc "Resource Manager REST APIs".
For example in the section above.
GET /subscriptions/SUBSCRIPTION_ID/resourcegroups?api-version=2015-01-01 HTTP/1.1
Host: management.azure.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
You would need to prepend Bearer to your token. Something like:
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_token}

Categories

Resources