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)
Related
I am trying to login on a website by use method requests POST.
ssn = requests.session()
data = {"LoginForm[email]":"gmail#gmail.com", "LoginForm[password]":"pw12345", "LoginForm[rememberMe]":0}
r = ssn.post("https://www.fshare.vn/site/login", data = data)
print(r.json)
# bound method Response.json of <Response [400]>
as I know, I missing a value in data is called "csrf-app" :
HTTP Header POST : _csrf-app=gXvuYHZnQpoA37zC1Yncpb1BMstVUqRcVdj9x1QHJqK1AoYoHlUV21G9jaya0Jjy9iJRrz1_nRIft4ywO0RD-g==&LoginForm[email]=gmail#gmail.com&LoginForm[password]=pw12345&LoginForm[rememberMe]=0
So how to get this value ""csrf-app" to post that along the other data ?
CSRF is used to avoid someone calling the APIs without the form.
You can refer to this post for more information. You should instead look for their login REST APIs, and see if they have any.
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
I'm relatively new to Python so would like some help, I've created a script which simply use the request library and basic auth to connect to an API and returns the xml or Json result.
# Imports
import requests
from requests.auth import HTTPBasicAuth
# Set variables
url = "api"
apiuser = 'test'
apipass = 'testpass'
# CALL API
r = requests.get(url, auth=HTTPBasicAuth(apiuser, apipass))
# Print Statuscode
print(r.status_code)
# Print XML
xmlString = str(r.text)
print(xmlString)
if but it returns a blank string.
If I was to use a browser to call the api and enter the cretentials I get the following response.
<Response>
<status>SUCCESS</status>
<callId>99999903219032190321</callId>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Dummy">
<authorFullName>jack jones</authorFullName>
<authorOrderNumber>1</authorOrderNumber>
</result>
</Response>
Can anyone tell me where I'm going wrong.
What API are you connecting to?
Try adding a user-agent to the header:
r = requests.get(url, auth=HTTPBasicAuth(apiuser, apipass), headers={'User-Agent':'test'})
Although this is not an exact answer for the OP, it may solve the issue for someone having a blank response from python-requests.
I was getting a blank response because of the wrong content type. I was expecting an HTML rather than a JSON or a login success. The correct content-type for me was application/x-www-form-urlencoded.
Essentially I had to do the following to make my script work.
data = 'arcDate=2021/01/05'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
r = requests.post('https://www.deccanherald.com/getarchive', data=data, headers=headers)
print(r.status_code)
print(r.text)
Learn more about this in application/x-www-form-urlencoded or multipart/form-data?
Run this and see what responses you get.
import requests
url = "https://google.com"
r = requests.get(url)
print(r.status_code)
print(r.json)
print(r.text)
When you start having to pass things in your GET, PUT, DELETE, OR POST requests, you will add it in the request.
url = "https://google.com"
headers = {'api key': 'blah92382377432432')
r = requests.get(url, headers=headers)
Then you should see the same type of responses. Long story short,
Print(r.text) to see the response, then you once you see the format of the response you get, you can move it around however you want.
I have an empty response only when the authentication failed or is denied.
The HTTP status is still ≤ 400.
However, in the header you can find :
'X-Seraph-LoginReason': 'AUTHENTICATED_FAILED'
or
'X-Seraph-LoginReason': 'AUTHENTICATED_DENIED'
If the request is empty, not even a status code I could suggest waiting some time between printing. Maybe the server is taking time to return the response to you.
import time
time.sleep(5)
Not the nicest thing, but it's worth trying
How can I make a time delay in Python?
I guess there are no errors during execution
EDIT: nvm, you mentioned that you got a status code, I thought you were literally geting nothing.
On the side, if you are using python3 you have to use Print(), it replaced Print
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()
I was making slack api calls through python library slackclient which is a wrapper around slack api. However, for some cases I need to make conventional api calls also with url and get/post method. I was trying to open a direct message channel with another user by my bot. The documentation - https://api.slack.com/methods/im.open says to "Present these parameters as part of an application/x-www-form-urlencoded querystring or POST body. application/json is not currently accepted."
Now in python, I can write,
url = 'https://slack.com/api/im.open'
headers = {'content-type':'x-www-form-urlencoded'}
data = {'token':BOT_TOKEN, 'user':user_id, 'include_locale':'true','return_im':'true'}
r= requests.post(url,headers,data )
print r.text
The message I get is {"ok":false,"error":"not_authed"}
I know the message is "not authed" although I use my bot token and another user id, my hunch is that I'm sending the request in wrong format because I just wrote it some way reading the documentation. I'm not sure how to exactly send these requests.
Any help?
since the Content-Type header is x-www-form-urlencoded sending data in form of dictionary does not work. you can try something like this.
import requests
url = 'https://slack.com/api/im.open'
headers = {'content-type': 'x-www-form-urlencoded'}
data = [
('token', BOT_TOKEN),
('user', user_id),
('include_locale', 'true'),
('return_im', 'true')
]
r = requests.post(url, data, **headers)
print r.text
The second parameter in requests.post is used for data, so in your request you're actually posting the headers dictionary. If you want to use headers you can pass arguments by name.
r= requests.post(url, data, headers=headers)
However this is not necessary in this case because 'x-www-form-urlencoded' is the default when posting form data.