requests.post makes a get request - python-3.x

I call requests.post but it ends up making a GET request.
post_body="""
{
...
}
"""
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
post_response = requests.post("https://...", data=post_body, headers=headers)
print(post_response.request.method)
The last print statement prints "GET". I expected to see "POST".
To debug this further, I changed the code like so:
req = requests.Request('POST', "https://...", data=booking_body, headers=headers)
prepared = req.prepare
print(prepared.method) // "POST"
s = requests.Session()
post_response = s.send(prepared)
print(post_response.request.method) // "GET"
The print statements print "POST" and "GET". What am I doing wrong?
PS:
$ python3 -V
Python 3.7.0

As stated in the comments, the issue was in redirect. The call was initially been made to http://... then redirected to https://.... Hence, the last method was GET.
Once the initial call was made to https://..., the issue was resolved.

Related

REST API Post method Recursive run returning Different data-probably data with error in Azure Functions

I am using REST API Post method and deployed to Azure functions .The First Run[immediate run post changes and deployment to azure] is success and subsequent runs are showing error in data and counts are not same as the first Run.Following is the code snippet that I am using.
` def __init__(self):
url = "https://login.microsoftonline.com/abcdefgh12345/oauth2/v2.0/token"
payload = 'grant_type=client_credentials&scope=api%AB1234567890CDE%.default'
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + "ABCDEFG",
'Cookie': 'XYZMANOP'
}
response = requests.request("POST", url, headers=headers, data=payload)
self.auth = response.json()`
Then I am using self.auth in other methods
Why is this happening and what is the solution???PS:When I try the code in local it works like a charm.
I tried extracting the access_token and added it in subsequent functions. But the result is also the same. Also I changed the schedule since access_token is valid only for 3600s and rescheduled to execute post 2 hours.But its returning same result

How to get a POST request using python on HERE route matching API?

I've tried to do a POST request using python's request library, which looked something like below:
url = "https://rme.api.here.com/2/matchroute.json?routemode=car&filetype=CSV&app_id={id}&app_code={code}"
response = requests.post(url,data='Datasets/rtHereTest.csv')
The response I've been getting a code 400
{'faultCode': '16a6f70f-1fa3-4b57-9ef3-a0a440f8a42e',
'responseCode': '400 Bad Request',
'message': 'Column LATITUDE missing'}
However, in my dataset, here I have all the headings that's required from the HERE API documentation to be able to make a call.
Is there something I'm doing wrong, I don't quite understand the POST call or the requirement as the HERE documentation doesn't explicitly give many examples.
The data field of your post request should contain the actual data, not just a filename. Try loading the file first:
f = open('Datasets/rtHereTest.csv', 'r')
url = "https://rme.api.here.com/2/matchroute.json?routemode=car&filetype=CSV&app_id={id}&app_code={code}"
response = requests.post(url, data=f.read())
f.close()
Here's what I use in my own code, with the coordinates defined before:
query = 'https://rme.api.here.com/2/matchroute.json?routemode=car&app_id={id}&app_code={code}'.format(id=app_id, code=app_code)
coord_strings = ['{:.5f},{:.5f}'.format(coord[0], coord[1]) for coord in coords]
data = 'latitude,longitude\n' + '\n'.join(coord_strings)
result = requests.post(query, data=data)
You can try to post the data using below format.
import requests
url = "https://rme.api.here.com/2/matchroute.json"
querystring = {"routemode":"car","app_id":"{app_id}","app_code":"{app_code}","filetype":"CSV"}
data=open('path of CSV file','r')
headers = {'Content-Type': "Content-Type: text/csv;charset=utf-8",
'Accept-Encoding': "gzip, deflate",
}
response = requests.request("POST", url, data=data.read().encode('utf-8'), params=querystring,headers=headers)
print(response.status_code)

KeyError when trying to send body to API via function parameter

Attempting to send a POST request to an API via a python function, and I'm unable to iterate through a list of strings and pass strings into the function.
Successfully tested this out in Postman (the request sends a string to the API in the form of "raw Body" as shown in Postman). Copied the code over from Postman to Python, and verified that also works. The problem is that if I change the static string to the function's parameter, I get a KeyError, however if I simply replace the parameter (which is a value, not a key), to a string, then the keyerror goes away.
This works...
payload = "{\"ids\":[\"cb5f9a97c0e749ab67409e78b4fcb11d\"]}" works
But none of these work (note the error code to the right); especially the first two that are exactly the same as above...
payload = "{\"ids\":[\"{0}\"]}".format(id) #gives KeyError: '"ids"'
payload = "{\"ids\":[{0}]}".format(id) #gives KeyError: '"ids"'
payload = "{'ids':'[{0}]'}".format(id) #gives KeyError: "'ids'"
payload = "{ids:[\"{0}\"]}".format(id) #gives KeyError: 'ids'
I also tried to modify the key ('ids') within the key/value pair, which resulted in NameErrors. Since this deviates from the known working example above, I don't think the below attempts are worth continuing to try...
payload = {ids:"[{0}]".format(id)} #gives NameError: name 'ids' is not defined
payload = {ids:"{0}".format(id)} #gives NameError: name 'ids' is not defined
payload = {ids:id} #gives NameError: name 'ids' is not defined
I even verified that the string produced from the list is in fact a string.
Full (relevant) code below:
def cs_delete(id):
print(id)
url = "https://api.crowdstrike.com/devices/entities/devices-actions/v2"
querystring = {"action_name":"hide_host"}
payload = "{'ids':['{0}']}".format(id)
headers = {
'Content-Type': "application/json",
'Authorization': "Bearer " + cs_auth,
'Accept': "*/*",
'Cache-Control': "no-cache",
'Host': "api.crowdstrike.com",
'Accept-Encoding': "gzip, deflate",
'Content-Length': "83",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
for host in dfList:
print(host)
cs_delete(host)
And for completeness, dfList shows as:
['2a9cf64988e6464f7d2ba7f305a612f3', '5ba4654e1dbe418f7b6361582e3d8f47', '7c6fc20572c241f664813f48bb36c340', 'ccbaf1ebe52042fc6b8269bf86732676']
double the outer curly bracket to escape it or format() will expect the input value should be applied for outer curly bracket rather than {0}
>>> id = 'cb5f9a97c0e749ab67409e78b4fcb11d'
>>> "{{'ids':[{0}]}}".format(id)
"{'ids':[cb5f9a97c0e749ab67409e78b4fcb11d]}"

How to convert curl command in shell script to python using requests library

I am trying to pull data from github api using specific search query and put it into a .txt file. I am able to do so by through curl and shell but I need to do it in python which I am very unfamiliar with. I have seen the requests library
I've tried using this website https://curl.trillworks.com/ and using requests library but I can't seem to wrap my head around how to format the request.
curl -H "Authorization: token xxx" 'https://api.github.com' "https://github.com/api/v3/search/repositories?q=Evidence+locker+Seed+in:readme" > evidencelockerevidence.txt
The above code does exactly what I need it to do (passes GHE token, calls api, stores it in a file) I just need help converting to python please.
EDIT: Solution was
import requests
headers = {
'Authorization': 'token xxx',
}
url = 'https://github.ibm.com/api/v3/search/repositories?q=Evidence+locker+Seed+in:readme'
response = requests.get(url, headers=headers)
print(response)
print(response.text)
All -H tags need to be specified in the headers key, and the url is the first positional argument.
import requests
headers = {
'Authorization': 'Bearer bearer_token',
}
url = 'https://github.com/api/v3/search/repositories?q=Evidence+locker+Seed+in:readme'
response = request.get(url, headers=headers)
print(response)
print(response.text)
That handles getting the data, now you have to worry about writing it to a file, which you can do with the open built-in function:
with open('path/to/evidencelockerevidence.txt', 'w') as file:
file.write(response.text)

Requests.get gives error Microsoft.SharePoint.Client.InvalidClientQueryException

I am calling sharepoint from my python requests.get code to pull sharepoint list items. However i am getting below error.
{"odata.error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The expression \"web/lists/GetByTitle(Useful Links)/items\" is not valid."}}}
This works fine when i call equivalent code from my angular code.
I tried to encode the url as it has spaces, brackets but it did not help.
i verified the url works fine by testing it from angular code and also postman tool.
#app.route('/getList',methods=['GET'])
def getList():
try:
api_token = request.args.get('api_token', '')
headers = {'Accept': 'application/json; odata=nometadata',
'Authorization': 'Bearer {0}'.format(api_token)}
api_url = '//<my company name>.sharepoint.com/teams/EIMGDS/_api/web/lists/GetByTitle(Useful Links)/items'
response = requests.get("https:"+urllib.parse.quote(api_url),params={},headers=headers, verify=False)
return response.text
except Exception as ex:
return jsonify({'message' : 'Error in Get List', 'detailedMessage': traceback.format_exc()}), 500
Expected result:
JSON having the sharepoint list details
Actual result:
{"odata.error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The expression \"web/lists/GetByTitle(Useful Links)/items\" is not valid."}}}

Resources