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
Related
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())
I have a curl command that works perfectly fine and gives me a HTTP 200.
curl -i -H "Authorization: Basic jadkfhjkafDSKJ12DD=" http://<ip>/LoadTest/rest/authentication-point/authenticate
The above API needs the authorization in base64 format and the details have to be passed as Headers. This is a GET request.
When I try to run the same in Python 2.7, I get Response [403]. Code below.
import requests
headers = {'Authorization': 'Basic jadkfhjkafDSKJ12DD='}
authurl = "http://<ip>/LoadTest/rest/authentication-point/authenticate"
r = requests.get(authurl, headers=headers)
print r.status_code
What am I missing here? How should i pass the authorization values exactly like I passed in the curl command? I've tried multiple ways but still end up getting HTTP 403 always. Kindly guide.
Thanks all for your inputs. This is the final solution. I found that there is proxy that is stopping the payload. So added the session to the request.
import requests
session = requests.Session()
session.trust_env = False
headers = {'Authorization': 'Basic jadkfhjkafDSKJ12DD='}
authurl = "http://<ip>/LoadTest/rest/authentication-point/authenticate"
r = session.get(authurl, headers=headers)
print r.status_code
Setting the trust_env=False ignores the following:
Authentication information from .netrc (code)
CA bundles defined in
REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE (code)
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'm working with an external API that unfortunately doesn't have that great error logging.
I use django 1.9.5 and requests 2.11.1.
When I make the following request with the built-in python server (python manage.py runserver) on my local machine, I get back a 200 status code, so this works fine.
r = requests.post(
'https://plazaapi.bol.com/offers/v1/%s' % product.ean, data=xml_to_send,
headers=headers)
headers are a dictionary of the date, an authorization code and the content-type
.
But as there is a problem with requests on GAE according to other answers on this site, I have tried to use the requests_toolbelt monkeypatch and urlfetch, but I always get back the following error then:
Request contains invalid authentication headers
Code with the monkeypatch:
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
r = requests.post(
'https://plazaapi.bol.com/offers/v1/%s' % product.ean, data=xml_to_send,
headers=headers)
and
from google.appengine.api import urlfetch
r = urlfetch.fetch(
url='https://plazaapi.bol.com/offers/v1/%s' % product.ean,
payload=xml_to_send,
method=urlfetch.POST,
headers=headers,
follow_redirects=False) # tried this, but has no effect.
The headers I'm setting are:
headers = {'Content-Type': 'application/xml',
'X-BOL-Date': date,
'X-BOL-Authorization': signature}
Is GAE changing my request and adding headers? If so, can I stop it
from doing so?
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).