How to generate json response from python? - 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)

Related

Failed to decode basic authentication token Python 3.10

I am creating script to send calls to API endpoints via simple python functions. I have the following function to retrieve my OAuth2 token (I will remove the URLs and credentials and nevermind the padding)
def get_new_token():
auth_server_url = "my auth url here"
client_id = "my client id here"
client_secret = "my secret here"
auth_headers = {'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'}
token_req_payload = {'grant_type': 'client_credentials'}
token_response = requests.post(auth_server_url,
data=token_req_payload, verify=False, allow_redirects=False,
auth=(client_id, client_secret), headers=auth_headers)
I am then successfully retrieving token with the following line:
return token_response.json()["access_token"]
Then, I can successfully make a request to one of the endpoints, here is my function (also, nevermind the padding):
def call_api_v1_accounts(token):
api_call_headers = {
'Content-Length': '10204',
'Content-Type': 'application/json',
'User-Agent': 'removed',
'Authorization': 'Bearer ' + token}
data = {"here": "is my payload"}
api_call_response = requests.post(my_url, headers=api_call_headers, data=json.dumps(data), verify=False)
print(api_call_response.text)
This request go through fine and I retrieve the information I need, here is the sample of response (I also removed actual data due to security reasons)
{"timestamp":"2022-08-09T10:24:29.713Z","account":{"id":"omitted"},"web":{"href":"omitted"},"sdk":{"token":"omitted"},"workflowExecution":{"id":"omitted","credentials":[{"id":"omitted","category":"ID","omitted":["WEB","API","SDK"],"api":{"token":"ommitted]}]}}
Here is my problem, finally. I have another function which uses the same token, function is below (nevermind the padding)
def call_api_netverify_acquisitions(token):
api_call_headers = {
'Content-Length': '10204',
'Content-Type': 'application/json',
'User-Agent': 'removed',
'Authorization': 'Basic ' + token}
data = {'mydata':'ishere'}
api_call_response = requests.post(my_url, headers=api_call_headers, data=json.dumps(data), verify=True)
print(api_call_response.text)
And the response I receive with it is the following:
{"message":"Failed to decode basic authentication token.","httpStatus":401,"requestUri":"endpoint_url_here"}
I really have no idea what's wrong with that? I printed the len(token) and it returned 867 so I decided I need to add one more symbol to that (so it can be divided by 4), I've added "=" or "===" or "=======" and the result is the same. I understand that one function uses 'Bearer' and other one uses 'Basic', but I still have no idea what to look for.
I am really struggling, please help.

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.

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

variable in python dictionary for http header construction

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)

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