variable in python dictionary for http header construction - python

New to python but I'm trying to use a variable within a dictionary that is used to construct a http header
This is what I have:
import requests
url = "https://sample.com"
auth = "sampleauthtoken"
headers = {
'authorization': "Bearer "<VARIABLE auth HERE>,
'cache-control': "no-cache"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
I have tried a few different combinations with no luck

If I understand you correctly you just want to concatenating the strings using the + operator:
import requests
url = "https://sample.com"
auth = "sampleauthtoken"
headers = {
'authorization': "Bearer " + auth, # -> "Bearer sampleauthtoken"
'cache-control': "no-cache"
}
response = requests.request("GET", url, headers=headers)
print(response.text)

Related

API Call is working in POSTMAN but API call with generated code is not working

API call is working in postman but when i am using generated code, it is not working
Generated code:
import requests
url = "http://services.XXX.com/rest/v2/verification"
payload = "{\r\n \"startDate\": \"2000-12-25\",\r\n \"endDate\": \"2000-12-31\",\r\n \"format\": \"CSV\"\r\n}"
headers = {
'authorization': "Bearer XXXXX",
'content-type': "application/json",
'cache-control': "no-cache",
'postman-token': "XXX"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
I have tried to execute after removing postman-token also but still getting below error:
{"message":"Internal Server Error: correlationId=V2-ee8fb1b098490b8665dd936e8472978b","type":"error","code":1}
When using passing json data in requests, you can pass a dictionary instead of string.
You can try this:
import requests
import json
url = "http://services.XXX.com/rest/v2/verification"
payload = "{\r\n \"startDate\": \"2000-12-25\",\r\n \"endDate\": \"2000-12-31\",\r\n \"format\": \"CSV\"\r\n}"
headers = {
'authorization': "Bearer XXXXX",
'content-type': "application/json",
'cache-control': "no-cache",
'postman-token': "XXX"
}
response = requests.post(url,json=json.loads(payload),headers=headers)
print(response.text)
You can change the payload variable, to a Json oblect this way:
Instead of:
payload = "{\r\n \"startDate\": \"2000-12-25\",\r\n \"endDate\": \"2000-12-31\",\r\n \"format\": \"CSV\"\r\n}"
You can use:
payload = {"startDate": "2000-12-25", "endDate": "2000-12-31", "format":"CSV"}

REST API post request results in successful request but not creation

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.

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)

python how do i put a variable in command string

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",
}

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