this might be a simple question but I couldn't find the problem why I'm not able to call post request to api url. I have cross-check with similar questions but mine still got problem.
This is the script
import requests
import json
#API details
url = "http://192.168.1.100:9792/api/scan"
body = {"service":"scan", "user_id":"1", "action":"read_all", "code":"0"}
headers = {'Content-Type': 'application/json'}
#Making http post request
response = requests.post(url, headers=headers, data=body, verify=False)
print(response)
#Decode response.json() method to a python dictionary for data process utilization
dictData = response.json()
print(dictData)
with open('scan.json', 'w') as fp:
json.dump(dictData, fp, indent=4, sort_keys=True)
Getting error
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
print(response) got return
<Response [200]>
if i run curl like below ok..and it will return the data from api post request
curl --header "Content-Type: application/json" --request POST --data '{"service":"scan","user_id":"1","action":"read_all","code":"0"}' http://192.168.1.100:9792/api/scan
using curl ok...but when i use requests/json python got problem...I think I might miss something here where I'm not able to detect. Please help and point me the right way. Thank you.
I had similar errors and dumping my data solved the issue. Try passing your body as a dump instead:
import requests
import json
#API details
url = "http://192.168.1.100:9792/api/scan"
body = json.dumps({"service":"scan", "user_id":"1", "action":"read_all", "code":"0"})
headers = {'Content-Type': 'application/json'}
#Making http post request
response = requests.post(url, headers=headers, data=body, verify=False)
print(response.json())
Related
I have tried using a rest client (ARC)for doing a post request to a private API and I am getting correct response but when I switch to python and did the same request using the python request package , the response is this
b'{"code":"Invalid Checksum","message":"Invalid Checksum"}'
I am using the same URL , header and body tag. Where can I possibly go wrong .
Here is the code snippet
import requests
import json
request_args = {"Id": -1,"startDate": "2018-01-13","endDate": "2018-01-14","ProviderId": 1}
headers = {'Authorization':'xxxxxx','Content-Type':'application/json','content-md5':'yyyy'}
base_url = "https://myendpoint"
response = requests.post(base_url,data=request_args, headers=headers)
print(response.content)
This is what I observed with f12 in chrome:
The payload here doesn't seem like json data since there is 89:42 in the front.
payload = ["auth",{"form":{"id":"xxxx","email":"xxx#xxx"}}]
resp = requests.post(url, json=payload, headers=headers)
print(resp.status_code)
payload = '89:42["auth",{"form":{"id":"xxxx","email":"xxx#xxx"}}]'
resp = requests.post(url, data=payload, headers=headers)
print(resp.status_code)
The status code of the above resp are both 400(bad request). How can I post it correctly?
[EDIT] I actually used Session to maintain the session. I'v also tried to change the content-type to application/json. But it didn't work. And as your can see in the picture, the default content-type seen with f12 is text/plain.
[EDIT] Some said the data or json argument must be a dict. Does it means that I should rewrite 89:42["auth",{"form":{"id":"xxxx","email":"xxx#xxx"}}] to change its type to dict? How should I do this?
From reading the requests documentation, you need to pass your payload as a dictoinary like this:
response = requests.post('https://httpbin.org/post', data = {'key':'value'})
I'm making a post request to some endpoint but always receiving 404 while doing it from python but when I do it with CURL everything works. Here's my python code:
import requests
def send_request(endpoint):
api_keys = {'Api-Key': API_KEY,
'Api-Username': API_USERNAME}
headers = {'content-type': 'multipart/form-data'}
request = requests.post(url = endpoint, data = api_keys, headers = headers)
print("STATUS CODE: %s" % request.status_code)
Thank you for the help!
Run
nc -lp 8080 (Linux) or nc -l 8080 (macOS)
and then make the request using curl to http://localhost:8080 and note the headers. Run the above command again and this time make the request using Python. Note the headers again and compare them with the ones you got when making the request with curl. Are they the same?
Perhaps User-Agent is missing. Make sure to add the missing headers in Python.
I managed to get 200 with following code:
def send_request(endpoint):
headers = {'Content-Type': 'multipart/form-data', 'Api-Key': API_KEY, 'Api-Username': API_USERNAME}
request = requests.post(url = endpoint, headers = headers)
print("Request Status Code: {}".format(request.status_code))
response = json.loads(request.text)
return response_text
All needed to be sent in headers
I am trying to write a python script that will make a request to a desktop application listening to 8080 port. The below is the code that I use to make the request.
import requests
payload = {"url":"abcdefghiklmnopqrstuvwxyz=",
"password":"qertyuioplkjhgfdsazxvnm=",
"token":"abcdefghijklmn1254786=="}
headers = {'Content-Type':'application/json'}
r = requests.post('http://localhost:9015/login',params = payload, headers=headers)
response = requests.get("http://localhost:9015/login")
print(r.status_code)
After making the request, I get a response code of 401.
However, when I try the same using the Postman app, I get a successful response. The following are the details I give in Postman:
URL: http://localhost:9015/login
METHOD : POST
Headers: Content-Type:application/json
Body: {"url":"abcdefghiklmnopqrstuvwxyz=",
"password":"qertyuioplkjhgfdsazxvnm=",
"token":"abcdefghijklmn1254786=="}
Can I get some suggestions on where I am going wrong with my python script?
You pass params, when you should pass data, or, even better, json for setting Content-Type automatically. So, it should be:
import json
r = requests.post('http://localhost:9015/login', data=json.dumps(payload), headers=headers)
or
r = requests.post('http://localhost:9015/login', json=payload)
(params adds key-value pairs to query parameters in the url)
I have used curl to send POST requests with data from files.
I am trying to achieve the same using python requests module. Here is my python script
import requests
payload=open('data','rb').read()
r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'), data=payload , verify=False)
print r.text
Data file looks like below
'ID' : 'ISM03'
But my script is not POSTing the data from file. Am I missing something here.
In Curl , I used to have a command like below
Curl --data #filename -ik -X POST 'https://IP_ADDRESS/rest/rest/2'
You do not need to use .read() here, simply stream the object directly. You do need to set the Content-Type header explicitly; curl does this when using --data but requests doesn't:
with open('data','rb') as payload:
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'),
data=payload, verify=False, headers=headers)
I've used the open file object as a context manager so that it is also auto-closed for you when the block exits (e.g. an exception occurs or requests.post() successfully returns).