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 }
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've been trying to make a Post Request to my CRM API. The CRM API is very vague:
"You can use POST request when you wish to create records. You POST a JSON encoded string to the servers and it will return a single instance of the record."
POST /{object_name}
Example:
Request URL (POST):
/accounts
Request Body (JSON):
{
"name": "testing API"
}
I've had plenty of success making GET requests regularly, but POST is not working out so easily.
url = "https://apiv4.reallysimplesystems.com/accounts?<KEY>"
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
headers = {
'Content-Type': 'application/json',
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
}
response = requests.post(url, headers=headers, data=payload)
I get a status code 200 when I run this, but I'm really looking for that 201. The only clue that I've got to follow at this point is that when I run:
response.json()
I get the error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I've tried switching the response parameters to json:
response = requests.post(url, headers=headers, json=payload)
I've tried ensuring that my payload is json by using json.dumps():
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
payload = json.dumps(payload)
And I've tried all sorts of other shenanigans that I can't even recall at this point. Does anyone have any idea where I'm going wrong here? The 200 status code makes me feel painfully close.
Replace <AUTH_TOKEN> with your auth token
url = "https://apiv4.reallysimplesystems.com/accounts/"
payload = {"name":"Ziggy"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH_TOKEN>',
}
response = requests.post(url, headers=headers, data=payload)
Problem solved:
import json
import requests
url = "https://apiv4.reallysimplesystems.com/accounts"
payload = {"name":"RSS Test Joe Bloggs","addresscounty/state":"Maryland","source":"Word of Mouth"}
payload = json.dumps(payload)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH KEY>'
}
response = requests.post(url, headers=headers, data=payload)
Rather than using Postman's code which included the in the URL and used :
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
I replaced it with a standard Authorization header. Secondly, I found that using json.dumps(payload) and json = payload was resulting in a Bad Request.
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)
I'm new to python and cannot figure out how to do the following.
I want to put a variable inside a command but its not working. The command is taking the variable name not its value.
The script below calls https with username and password to get a token. I token is returned . I then need to use the token to create a user.
I'm having issues with it, "token" in the iplanet pair is not getting expanded correctly. It is set correctly as I can print it out before the command. So token would contain something like "AQIC5wM2LY4Sfcydd5smOKSGJT" , but when the 2nd http call is made it gets passed the word token , rather than tokens value.
import requests
import json
url = "https://www.redacted.com:443/json/authenticate"
headers = {
'X-Username': "user",
'X-Password': "password",
'Cache-Control': "no-cache",
}
response = requests.request("POST", url, headers=headers)
tokencreate = json.loads(response.text)
token=tokencreate['tokenId']
print token
url = "https://www.redacted.com:443/json/users"
querystring = {"_action":"create"}
payload = "{\r\n\"username\":\"Patrick\",\r\n\"userpassword\":\"{{userpassword}}\",\r\n\"mail\":\"patrick#example.com\"\r\n}"
headers = {
'iPlanetDirectoryPro': "token",
'Content-Type': "application/json",
'Cache-Control': "no-cache",
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
It's because you are passing the string 'token' when you mean to pass the variable token
here you create the token:
tokencreate = json.loads(response.text)
token=tokencreate['tokenId']
print token
But you don't use the actual variable, it should look like this:
payload = "{\r\n\"username\":\"Patrick\",\r\n\"userpassword\":\"{{userpassword}}\",\r\n\"mail\":\"patrick#example.com\"\r\n}"
headers = {
'iPlanetDirectoryPro': token,
'Content-Type': "application/json",
'Cache-Control': "no-cache",
}
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.