I am trying to pass header in post method for generating access token. however I am getting the wrror about invalid syntax. my header code is as below
headers=("Authorization: Basic RXadsdsdsdsdsdsdsdsdjkfhsuidhsuihf==","Content-Type: application/x-www-form-urlencoded")
headers=('Authorization': 'Basic RXadsdsdsdsdsdsdsdsdjkfhsuidhsuihf==','Content-Type': 'application/x-www-form-urlencoded')
Assuming that you are using Requests, headers should be a dictionary, so:
headers={
"Authorization": "Basic RXadsdsdsdsdsdsdsdsdjkfhsuidhsuihf==",
"Content-Type": "application/x-www-form-urlencoded"
}
You can try the below code:
auth_token = "Basic {}".format(token)
headers = {'Content-Type': 'application/json', 'Authorization': auth_token}
Related
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.
I have an external API with its Content-Type, Authorization key, and tenant fields. The description of API is like this:
URL: https://url_address.com/
method: POST
Header:
Content-Type: application/json
Authorization: Basic asfvasvGasfssfafssDGDggGDgDSggsdfgsd=
Body: -> raw :
{
"Tenant" : "devED"
}
I try to fetch these data from my django views with this:
headers = {'Content-Type': 'application/json', 'Authorization': 'Basic asfvasvGasfssfafssDGDggGDgDSggsdfgsd='}
Body = { "Tenant": 'devED' }
GetAPI_response = requests.post('https://url_address.com/', headers=headers, params=Body).json()
But it says errors like:
{'Message': 'Request data is in Bad Format.'}
Please suggest how can I fix this?
As of version 2.4.2, requests.post can be passed a json parameter that will be automatically encoded and will set the Content-Type header to application/json meaning you don't have to set it yourself
headers = {'Authorization': 'Basic xxxxxxxxxxxxxx'}
body = {'Tenant': 'devED'}
response = requests.post('https://url_address.com/', headers=headers, json=body)
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",
}
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)
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 }