From Python I make request to Rails app, and get this response:
{u'answer': u'ok'}
and in Rails side code like that:
#res = {'answer'=> 'ok'}
render json: #res
May this problem on python side? Here code of python:
import requests
import json
URL1 = 'http://'
PARAMS = {'login': 'asd'}
r = requests.get(url = URL1, params = PARAMS)
data = r.json()
print(data)
How I can get clear json
You can try as data = r.as_json
You are specifically parsing the JSON contained in the response body into Python objects using r.json(). Use r.text to see the textual representation of the response body.
In a Rails controller you can do:
render :json => data.to_json and return
In the CLI you'd do:
puts data.to_json
Make sure to include json or a compatible gem in your CLI code.
Related
I am following some example code in the mediawiki api (see link at the bottom) to get a response in json format that looks something like the following:
"login": {
"lguserid": 21,
"result": "Success",
"lgusername": "William"
}
Unfortunately, I am not getting anything similar to that and instead just get a response that looks as follows:
<Response [200]>
Below is the example code that I'm almost using verbatim at this point, to no avail.
#!/usr/bin/python3
"""
login.py
MediaWiki API Demos
Demo of `Login` module: Sending post request to login
MIT license
"""
import requests
USERNAME = "my_bot_username"
PASSWORD = "my_bot_password"
S = requests.Session()
URL = "https://www.mediawiki.org/w/api.php"
# Retrieve login token first
PARAMS_0 = {
'action':"query",
'meta':"tokens",
'type':"login",
'format':"json"
}
R = S.get(url=URL, params=PARAMS_0)
Again, R is supposed to be in json format instead it is just a http response code not in json format which causes the very next line of the example script (see link at the bottom) fail.
Is the example code outdated or can anyone spot why the code above is not returning a response in json format?
EDIT: The version of mediawiki I am using is 1.17.0
https://www.mediawiki.org/wiki/API:Login#Python
You have to use response.json() to get a json object :
R = S.get(url=URL, params=PARAMS_0)
DATA = R.json()
I am trying to translate a specific curl method into Python's requests module to upload a file to to an api. My standard method that works for non-file requests looks like this:
import requests
requestObject = requests.Session()
standard_headers = {header1:headerValue1,header2:headerValue2}
payload = {key1:value1,key2:value2}
url = 'https://myUrl.com/apiCall'
requestObject.post(url,headers=standard_headers, json=payload)
This works for non-file requests that I need to make to the API. However for file uploads, the API documentation shows a method using curl:
curl -XPOST -H 'header1' -H 'header2 'https://myUrl.com/apiCall' \
-F 'attachment=#/path/to/my/file' \
-F '_json=<-;type=application/json' << _EOF_
{
"key1":"keyValue1",
"key2":"keyValue2"
}
_EOF_
I tested the curl command and it works successfully.
My question is how do I translate that curl method using the << _EOF_ method in Python requests. One idea I had was simply to use the 'files' option in the requests module:
requestObject = requests.Session()
standard_headers = {header1:headerValue1,header2:headerValue2}
payload = {key1:keyValue1,key2:keyValue2}
url = 'https://myUrl.com/apiCall'
file_to_upload = {'filename': open('/path/to/my/file', 'rb')}
requestObject.post(url,headers=standard_headers, files=file_to_upload, json=payload)
But that does not seem to work as the necessary json parameters (the values in payload) do not appear to get passed to the file upload
I also tried specifying the json parameters directly into the file_to_upload variable:
requestObject = requests.Session()
standard_headers = {header1:headerValue1,header2:headerValue2}
url = 'https://myUrl.com/apiCall'
file_to_upload = {'attachment': open('/path/to/my/file', 'rb'),'{"key1":"keyValue1","key2":"keyValue2"}'}
requestObject.post(url,headers=standard_headers, files=file_to_upload)
Similar result, it seems as though I am not passing the necessary json values correctly. I tried a few other ways but I am overlooking something. Any insight into how I should structure my request is appreciated.
Ok I managed to get it to work and posting for anyone who might need help in the future.
The trick was to include the _json key in the data field. My code ended up looking like so:
import requests
requestObject = requests.Session()
standard_headers = {header1:headerValue1,header2:headerValue2}
json_fields = json.dumps({
"key1": "key1Value",
"key2": "key2Value"
})
payload = {"_json":json_fields)
file = {"attachment": /path/to/my/file}
url = 'https://myUrl.com/apiCall'
requestObject.post(url,headers=standard_headers, files=file, data=payload)
Hope that helps some future person.
I have a web server and can run python on it, like this:
import os
from urllib.parse import parse_qsl
def main():
thestring = os.environ["QUERY_STRING"]
parameter_dict = dict(parse_qsl(thestring))
print(parameter_dict)
print("Content-Type: text/plain")
print("")
main()
If I hit is like this: http://127.0.0.1/web.py?hello=world
I'll get a nice little hash:
{'hello': 'world'}
That works just fine for my purposes. Now what I'm trying to do is make this webserver accept json input.
I'm using this code to 'throw' json at the URL
body = {
"username":"user1",
"folder":"folder1"
}
req = urllib.request.Request("http://127.0.0.1/web.py")
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)
content = json.loads(response.read().decode("utf-8"))
print(content)
But what do I need to do in my top section of code to have web.py 'accept' the json and be able to use it? Ideally just put the json into a dict. I bet this is just something really simple and I'm just missing a basic command. Thank you in advance!
I'm trying to retrieve the response json data by a web site that I call.
The site is this:
WebSite DriveNow
On this page are shown on map some data. With browser debugger I can see the end point
end point
that sends response data json.
I have use this python to try scrape the json response data:
import requests
import json
headers = {
'Host': 'api2.drive-now.com',
'X-Api-Key': 'adf51226795afbc4e7575ccc124face7'
}
r = requests.get('https://api2.drive-now.com/cities/42756?expand=full', headers=headers)
json_obj = json.loads(r.content)
but I get this error:
hostname doesn't match either of 'activityharvester.com'
How I can retrieve this data?
Thanks
I have tried to call the endpoint that show json response using Postam, and passing into Header only Host and Api-Key. The result is the json that i want. But i i try the same call into python i recive the error hostname doesn't match either of 'activityharvester.com'
I don't understand your script, nor your question. Why two requests and three headers ? Did you mean something like this ?
import requests
import json
headers = {
'User-Agent': 'Mozilla/5.0',
'X-Api-Key':'adf51226795afbc4e7575ccc124face7',
}
res = requests.get('https://api2.drive-now.com/cities/4604?expand=full', headers=headers, allow_redirects=False)
print(res.status_code, res.reason)
json_obj = json.loads(res.content)
print(json_obj)
I used Postman to send a raw request to Jetstar website to get the flight details. And I wanted to use python script to do the same thing using requests library, but I cannot get back the correct response.
Here what I have done in Postman:
And a simple script I used to send post request:
import requests
files = {'file': open('PostContent.txt', 'rb')}
if __name__ == "__name__"):
url = "http://www.jetstar.com/"
r = requests.post(url, files = files)
print(r.text)
When I run the python script, I always get the welcome page not flight details. I am not sure what is error?
Note: The PostContent.txt contains the form-data in raw text when I search for flights.
I used Chrome Dev Tool to capture the POST request when I search for a specific flight date. And it is the Form Data in the Headers.
Try using a dictionary instead of a FILE. The FILE is supposed to be for posting a FILE, not a FORM-ENCODED post, which is probably what the site expects.
payload = {
'DropDownListCurrency': 'SGD'
}
r = requests.post("http://httpbin.org/post", data=payload)
You use a key file which is wrong for this type of request. Also your sample code isn't working! Just paste working code here...
import requests
import logging
logging.basicConfig(level=logging.DEBUG)
payload = {"__EVENTTARGET":"",
"__EVENTARGUMENT":"",
"__VIEWSTATE":"/wEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFJ01lbWJlckxvZ2luU2VhcmNoVmlldyRtZW1iZXJfUmVtZW1iZXJtZSDCMtVG/1lYc7dy4fVekQjBMvD5",
"pageToken":"",
"total_price":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$RadioButtonMarketStructure":"RoundTrip",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin1":"Nadi (NAN)",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination1":"Melbourne (Tullamarine) (MEL)",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate1":"14/01/2015",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate1":"16/02/2015",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListCurrency":"AUD",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin2":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination2":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate2":"16/02/2015",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate2":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin3":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination3":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate3":"27/12/2014",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate3":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin4":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination4":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate4":"03/01/2015",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate4":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin5":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination5":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate5":"10/01/2015",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate5":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin6":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination6":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate6":"17/01/2015",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate6":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_ADT":1,
"ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_CHD":0,
"ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_INFANT":0,
"ControlGroupSearchView$AvailabilitySearchInputSearchView$RadioButtonSearchBy":"SearchStandard",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMultiCityOrigin1":"Origin",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMultiCityDestination1":"Destination",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureMultiDate1":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMultiCityOrigin2":"Origin",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMultiCityDestination2":"Destination",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureMultiDate2":"",
"ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMultiPassengerType_ADT":1,
"ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMultiPassengerType_CHD":0,
"ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMultiPassengerType_INFANT":0,
"ControlGroupSearchView$AvailabilitySearchInputSearchView$numberTrips":2,
"ControlGroupSearchView$AvailabilitySearchInputSearchView$ButtonSubmit":""}
if __name__ == "__main__":
url = "http://booknow.jetstar.com/Search.aspx"
r = requests.post(url, data=payload)
print(r.text)