Regarding the new Bit.ly API in Python - python

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

Related

Calling private API with python

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.

BambooHR Python GET Request returning Error 401

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

(Discord api) Change nickname on a server with python requests

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

How to get share's url of a file using Dropbox python API?

I want to print share's Link from a file using API dropbox = python
My code:
import requests
import json
url = "https://api.dropboxapi.com/2/sharing/create_shared_link"
headers = {
"Authorization": "Bearer ACCESS_TOKEN_REDACTED",
"Content-Type": "application/json"
}
data = {
"path": "/132005.jpg"
}
r = requests.post(url, headers=headers, data=json.dumps(data))
Now i want to get url to share like:
https://www.dropbox.com/s/o3hniburr4byytu/132005.jpg?dl=0
What print??? Thank bro
Possible options you can check or try out.
print r.json()
print r.content
print r.text
print r.status_code

PUT Request to REST API using Python

For some reason my put request is not working and I am getting syntax errors. I am new to Python but I have my GET and POST requests working. Does anyone see anything wrong with this request and any recommendations? I am trying to change the description to "Changed Description"
PUT
#import requests library for making REST calls
import requests
import json
#specify url
url = 'my URL'
token = "my token"
data = {
"agentName": "myAgentName",
"agentId": "20",
"description": "Changed Description",
"platform": "Windows"
}
headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data:data}
#Call REST API
response = requests.put(url, data=data, headers=headers)
#Print Response
print(response.text)
Here is the error I am getting.
Traceback (most recent call last):
line 17, in <module>
headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data:data}
TypeError: unhashable type: 'dict'
Syntax error in because of = sign in your headers dictionary:
headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data=data}
It should be:
headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", 'data':data}
See data=data is changed with 'data':data. Colon and Single Quotes.
And are you sure you will be sending data in your headers? Or you should replace your payload with data in your put request?
Edit:
As you have edited the question and now you are sending data as PUT request's body requests.put(data=data) so there is no need of it in headers. Just change your headers to:
headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json"}
But as you have set your Content-Type header to application/json so I think in your PUT request you should do
response = requests.put(url, data=json.dumps(data), headers=headers)
that is send your data as json.
The problem is that you try to assign data to the data element in your dictionary:
headers = { ..., data:data }
That can't work because you can't use a dictionary as a key in a dictionary (technically, because it's not hashable).
You probably wanted to do
headers = { ..., "data":data }

Categories

Resources