I am fairly new to API, Si I followed some tutorials and posts here but I am having issues calling an API using client ID and secret, the API uses bearer token for authentication, I cant get authenticated properly. Here is what I am using:
import base64
import requests
client_id = "abcd123"
client_secret = "EFGH456"
authorization = base64.b64encode(bytes(client_id + ":" + client_secret, "ISO-8859-1")).decode("ascii")
headers = {
"Authorization": f"Basic {authorization}",
"Content-Type": "application/x-www-form-urlencoded"
}
body = {
"grant_type": "client_credentials"
}
response = requests.post("https://mywebsite/api/", data=body, headers=headers)
print(response.text)
I am not sure how to get and store the bearer token and what is the problem with the code I am using.
Thank you in advance.
You should prepend Bearer to the authorization header value, not Basic. I'm assuming that you've properly encoded your token.
headers = {
"Authorization": f"Bearer {authorization}",
"Content-Type": "application/x-www-form-urlencoded"
}
Check out this article for an explanation of the difference.
Related
Seemingly the bit.ly API has been updated a lot in recent years. Here is the website of the latest API documentation https://dev.bitly.com/api-reference
I am trying to do the simplest operation, i.e., shortening a long URL.
I have generated a token following the instructions, and below is the code I tried following the example (https://dev.bitly.com/api-reference/#createBitlink) where I used my token instead of the string "my token" here:
import requests
headers = {
"Authorization": "Bearer {my token}",
"Content-Type": "application/json",
}
data = '{ "long_url": "https://dev.bitly.com", "domain": "bit.ly"}'
response = requests.post(
"https://api-ssl.bitly.com/v4/shorten", headers=headers, data=data
)
But the response is 403.
Is there anyone who is familiar with the bit.ly API?
Any help will be appreciated!
A related question: getting bit.ly to return shortened URL
Sorry for the confusion...
It is seemingly okay now.
Below is an example extended from https://dev.bitly.com/api-reference/#createBitlink
import requests
import sys
input_url = sys.argv[1]
longurl = "https://" + input_url if not input_url.startswith("https://") else input_url
print(longurl)
token = "find your token at https://app.bitly.com/settings/api/"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
data = '{ "long_url": "' + longurl + '", "domain": "bit.ly"}'
# print(data)
response = requests.post(
"https://api-ssl.bitly.com/v4/shorten", headers=headers, data=data
)
try:
print(response.json()["link"])
except:
print(response)
print(response.json())
python bitly.py https://stackoverflow.com/questions/75279574
https://stackoverflow.com/questions/75279574
https://bit(dot)ly/3DqI7Ea
I am working on a python script that generates the access token.
I am working on API calls for the first time.
I am getting the below error:
jsonResponse: {
'error_description': 'Grant type is not set', 'error': 'invalid_request'
}
I tried all the different grant_types but getting the same error.
Could someone help me?
import requests
import json
myToken = 'https://......../internal/access_token'
headers =
{
"Accept": "application/json",
'Authorization': 'Bearer {}'.format(myToken),
"Content-Type": "application/x-www-form-urlencoded",
"Grant_Type":"client_credentials",
"scope": 'api-customer',
"client_id": '<Clientid>',
"client_secret": '<secret>'
}
response = requests.post(myToken, headers = headers)
jsonResponse = response.json()
print('jsonResponse: ' + str(jsonResponse))
Thanks
I am trying to fetch data from Bamboo HR API using python but it is returning me Error 401 (which as per their documentation means "Your API Key is missing"). I actually tried to do the same thing using Google Apps Script and there it is working perfectly fine. Can anyone please suggest what am i doing wrong here in python. Its driving me nuts.
Documentation Link - https://documentation.bamboohr.com/reference#get-employees-directory-1
Following is the code I am using in Python
import requests
url = "https://api.bamboohr.com/api/gateway.php/companyDomain/v1/employees/directory"
headers = {
"Accept": "application/json",
"Authorization": "Basic API-KEY"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
Following is the code I used in Google Apps Script
function myFunction() {
var url = "https://api.bamboohr.com/api/gateway.php/companyDomain/v1/employees/directory";
var apiKey = "API-KEY";
var authHeader = "Basic " + Utilities.base64Encode(apiKey + ":x");
var res = UrlFetchApp.fetch( url, { "headers":{"Authorization": authHeader } } );
var content = res.getContentText();
Logger.log(res);
Logger.log(content);
}
You need to specify your API key in the URL.
import requests
your_api_key = "your_api_key"
url = f"https://{your_api_key}:x#api.bamboohr.com/api/gateway.php/subdomain/v1/employees/directory"
headers = {
"Accept": "application/json",
"Authorization": your_api_key
}
r = requests.get(url, headers=headers)
df = r.json()
df= pd.json_normalize(df["employees"])
Then this will work
I am trying to change the nickname of my account on a website but it's not working. This is the code I used.
import requests
token=input('Enter your token: ')
payload = {
'nick': 'new nickname'
}
headers = {
'authorization': token
}
r = requests.patch('https://discord.com/api/v9/guilds/8652577727676008/members/#me', data=payload, headers=headers)
request method and url | authorization | data
import requests, json
token=input('Enter your token: ')
payload = {
"nick": "tester"
}
headers = {
"Authorization": f"Bot {token}",
"Content-Type": "application/json",
}
r = requests.patch('https://discord.com/api/v9/guilds/8652577727676008/members/#me', data=json.dumps(payload), headers=headers)
print(r.content)
I'm new in apis too. But the mistakes you've made are:
Headers
The authorization should be Bot {token} not just {token} (in case
of bots)
You have not defined the content type
Data
Making the data a json string instead of a dict object worked for me
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}