I´m using Python 2.7.7 to send a post request to a website. Im using the requests module and my code looks like this: (NAME and PASS are substituted)
r = requests.post("http://play.pokemonshowdown.com/action.php", data="act=login&name=NAME&pass=PASS&challengekeyid="+challstrarr[2]+"&challenge="+challstrarr[3])
print(r.text)
print(r.json())
r.text returns just a blank line, r.Json returns this error: "ValueError: No JSON object could be decoded"
The website i´m requesting has the following tutorial:
you'll need to make an HTTP POST request to http://play.pokemonshowdown.com/action.php with the data act=login&name=USERNAME&pass=PASSWORD&challengekeyid=KEYID&challenge=CHALLENGE
Either way, the response will start with ] and be followed by a JSON object which we'll call data."
I´m not sure if the post request response is faulty (and hence the blank line) or if its not faulty and the json parsing is off
You should pass a dictionary object to the post function (the data argument), only in the get method you should pass a query string:
postData = {
#put you post data here
}
r = requests.post("http://play.pokemonshowdown.com/action.php", data=postData)
print(r.text)
print(r.json())
Related
I have a python code thats supposed to create a json file that i use as the data in my post requests.
The variable looks like this:
request="""{"QueryString":"{\\"search_type\\":5,\\"project_id_list\\":[\\"1\\"],\\"user_key\\":\\"a\\",\\"options\\":{\\"pagination\\":{\\"page_num\\":1,\\"page_size\\":200},\\"projection\\":{\\"name\\":1},\\"condition_group\\":{\\"conjunction\\":\\"AND\\",\\"conditions\\":[],\\"groups\\":[]},\\"facet\\":{\\"fields\\":[],\\"type\\":0,\\"update_one\\":false},\\"groups\\":[],\\"sort\\":[]},\\"search_types\\":[]}","SearchType":4}"""
When I print the above variable I get the following output:
{"QueryString":"{\"search_type\":5,\"project_id_list\":[\"1\"],\"user_key\":\"a\",\"options\":{\"pagination\":{\"page_num\":1,\"page_size\":200},\"projection\":{\"name\":1},\"condition_group\":{\"conjunction\":\"AND\",\"conditions\":[],\"groups\":[]},\"facet\":{\"fields\":[],\"type\":0,\"update_one\":false},\"groups\":[],\"sort\":[]},\"search_types\":[]}","SearchType":4}
When I use the following output on my postman request it works as I expect it to. But when I use the same variable to send the http request with the following function I get an error.
url = 'www.myurl.com'
body =request
headers = {
'Token': 'sas'}
r = requests.post(url, data=body, headers=headers)
print(r.text) #prints an error {"statusCode":-1,"errMsg":"unexpected end of JSON input"}
Why is my output working on postman but not in python itself?
As the code is working in postman , You can generate python code from postman itself:
I've been pulling my hair out the past couple of days trying to get a Python http request to work. I can get it working using Postman, but for some reason it just won't work no matter what I do in Python. I'm hoping if I can compare some raw version of the two requests I can see what the differences might be.
For Postman, I'm simply POSTing like this:
The header is an authentication token, identical to the one I'm using in Python. Here's my python code:
text = open(filepath, 'rb').read()
body = aiohttp.formdata.FormData()
body.add_field('files', text, filename=f'{filepath}')
resp = await session.post(url=self.ip_address + '/upload',
headers={'Authorization': f'Bearer {self.jwt}'},
data={'files': body})
resp.raise_for_status()
html = await resp.text()
return html
But I get a 500 response:
[2019-09-05T18:50:04.751Z] error TypeError: Cannot destructure
property refId of 'undefined' or 'null'.
at upload (/home/ubuntu/project.strapi/node_modules/strapi-plugin-upload/controllers/Upload.js:26:66)
at process._tickCallback (internal/process/next_tick.js:68:7)
I resolved this by changing the parameter in post() to just data=body
i'm trying to send a post request to my express server using python, this is my code:
import requests
print("started");
URL = "http://localhost:5000/api/chat"
PARAMS = {'ID':"99","otherID":"87",'chat':[{"senderName":"tom","text":"helloworld"}]}
r = requests.post(url = URL, data = PARAMS)
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)
but when I recieve the call, I get an empty object on my Node server, am I missing something?
(With postman it works fine so its not the server)
typically requests library differentiates on the type of request depending on the param used to make the request. Meaning if you intend to make a JSON post then one should use the json param like so:
response = requests.post(url=URL, json=PARAMS)
what this does is set the accompanying headers which is why when your express server attempts to parse it, it comes back empty
This works fine, I can get data returned:
r = urllib2.Request("http://myServer.com:12345/myAction")
data = json.dumps(q) #q is a python dict
r.add_data(data)
r=urllib2.urlopen(r)
But doing the same with requests package fails:
r=requests.get("http://myServer.com:12345/myAction", data=q)
r.text #This will return a message that says method is not allowed.
It works if I make it a post request: r=requests.post("http://myServer.com:12345/myAction", data=json.dumps(q))
But why?
According to the urllib2.urlopen documentation:
the HTTP request will be a POST instead of a GET when the data parameter is provided.
This way, r=urllib2.urlopen(r) is also making a POST request. That is why your requests.get does not work, but requests.post does.
Set up a session
import session
session = requests.Session()
r = session.get("http://myServer.com:12345/myAction", data=q)
print r.content (<- or could us r.raw)
I am trying to make a post request within the Matchbook API.
I have logged in and I got below "Session- Tocken":
{"session-token":"xxxx_b0b8a6f22a82396b6afcfa344f3022","user-id":xx685,"role":"USER"}
However, I am not sure how to make the post request. See below code used:
headers = {"session-token" : "xxxx_b0b8a6f22a82396b6afcfa344f3022"}
r = requests.post('https://api.matchbook.com/edge/rest/reports/v1/offers/current/?odds-type=DECIMAL&exchange-type=binary¤cy=EUR, headers = headers')
print r.text
Below is the error message that I got. It does not make sense to me because I logged in successfully and got the above session-token in response.
{"errors":[{"messages":["You are not authorised to access this resource. Login to continue."]}]}
Am I properly indicating the session-token in the header information of the post request?
You need to pass headers argument in post function.
headers = {"session-token" : "xxxx_b0b8a6f22a82396b6afcfa344f3022"}
response = requests.post('https://api.matchbook.com/edge/rest/reports/v1/offers/current/?odds-type=DECIMAL&exchange-type=binary¤cy=EUR', headers=headers)
also if you need to get an json response, just call json() function on response variable.
something like response.json()