the function looks like this:
import requests
import json
def parse(s):
r = requests.post('http://166.111.139.15:9000/?properties%3d%7b%22annotators%22%3a%22tokenize%2cssplit%2cpos%2clemma%2cparse%22%2c%22outputFormat%22%3a%22json%22%7d%0a', data=s)
return r.json()
print parse("I am a student")
And when I use it in Django, the web page shows:
"No JSON object could be decoded".Why?
No JSON object could be decoded is an exception message raised at r.json(). If your response is not a valid json object you can still retrieve it with r.text. Even if you are sure your response is always a valid json object, you should still check whether server returned a success code. If there's an internal server error (code 500), you won't get a valid json response!
import requests
def parse(s)
r = requests.post('http://someserver.com', data=s)
if r.status_code !== 200:
return "There was a problem: {} !".format(r.text)
return r.json()
Related
I'm new to Python. I'm trying to make a change in the Json body that I get in an exchange response using the requests library.
I want to do something like:
import json
import requests
def request_and_fill_form_in_response() -> requests.Response():
response = requests.get('https://someurl.com')
body_json = response.json()
body_json['some_field'] = 'some_value'
response.content = json.dumps(body_json)
return response
In this particular scenario I'm only interested of updating the response.content object (regardless of if it is a good practice or not).
Is this possible?
(btw, the code above throws 'AttributeError: can't set attribute' error, which is pretty much self-explanatory, but I want to make sure I'm not missing something)
You can rewrite the content in this way:
from json import dumps
from requests import get, Response
def request_and_fill_form_in_response() -> Response:
response = get('https://mocki.io/v1/a9fbda70-f7f3-40bd-971d-c0b066ddae28')
body_json = response.json()
body_json['some_field'] = 'some_value'
response._content = dumps(body_json).encode()
return response
response = request_and_fill_form_in_response()
print(response.json())
and the result is:
{'name': 'Aryan', 'some_field': 'some_value'}
but technically _content is a private variable and there must be a method as a setter to assign a value to it.
Also, you can create your own Response object too. (you can check the response methods here)
I'm trying to write the output of an API 'get' request to a file. I know the function works as the output of the request is returned successfully and in full in shell.
The function creates the file, but the file only includes the status code for the get request - can anyone help me understand why? Still pretty new to Python and very new to calling APIs...
def user_info(token):
heads = {"Authorization": "bearer " + token, "Content-type": "application/json"}
url = "xxxxx"
request = req.get(url, headers=heads)
with open('userdata.txt', 'w') as f:
f.write(str(request))
if request.status_code == 200:
return request.json()
else:
return "User Info FAILED! Failure code: {}, error: {}".format(request.status_code,request.json()['error'])
The file just contains:
<Response [200]>
Thanks!
A Response object in the requests module when called as a string will return its status code as detailed in the Response python code
def __repr__(self):
return '<Response [%s]>' % (self.status_code)
If you want to write the json from the response as a string then you can use the built in json module and use its dumps method to dump it as a string not a dict.
import requests
import json
with open("myfile.txt", "w") as output:
resp = requests.get("https://jsonplaceholder.typicode.com/todos/1")
output.write(json.dumps(resp.json()))
I'm trying to send two files in a json object with flask restfull and send_file.
When I try to access the json object on client side i get this error:
TypeError: Object of type 'Response' is not JSON serializable
This is what i do i my flask app:
class Download(Resource):
def get(self):
try:
return {"file1" : send_file('uploads/kode.png'), "file2" : send_file('uploads/kode.png')}, 200
except:
return {"message" : "File not found!"}, 404
How can I return a json of files?
If I do the same thing with only one file without wrapping the send_file() in {}, I can access that file on the front end with java script.
You mean like:
return send_file('path/to/file.png')
That works, because Flask's send_file function actually returns a Response object.
This is also valid code (as of flask version 1.1.0):
return {"message" : "File not found!"}, 404
Here you're returning a dictionary with the key 'message' and value 'File not found!'. Flask will turn this into a Response object, with a status code of 404.
That dictionary is jsonified automatically (as of flask version 1.1.0).
When you try to return this:
return {"file1" : send_file('uploads/kode.png')}, 200
The Response object returned by send_file is then jsonified, hence the exception:
TypeError: Object of type 'Response' is not JSON serializable
The obvious way to make this work is that the frontend should make a separate request to the server for each image, passing some kind of ID which the Flask route function should then obtain and use to work out the filepath, then ultimately: return sendfile(filepath).
If you really want to send several images in one JSON response, you could look at base64 encoding the image and making a data_uri string which can be JSON serialized. However unless you really need that data to be passed as JSON, the former option is probably the go-to.
I think your except is too broad. but to get a json object back, import json and its object.json()
import json
try:
return file.json()
except Exception as e:
print(e)
or your can import the json library from flask
from flask import jsonify
def myMethod():
....
response = jsonify(data)
response.status_code = 200 # or 400 or whatever
return response
I'm sending a simple REST API call in python:
import json
import requests
import time
url = 'https://server:9899/123456789/open.scan'
data = {'alpha':'one','beta':'two'}
print 'Sending open.scan command: ' + str(data)
try:
response = requests.post(url, data=data, verify=false)
print response.status_code
except:
print "failed"
This all works correctly and triggers the API. However, if the apikey I feed is bad I get back a 405 error (as expected?).
The issue I'm having is this:
When I issue this API call over a web browser as simply:
https://server:9899/api/wrongapikeyhere/open.sesame
The page returned to me actually states "Wrong API key used"
I'm trying to figure out how to get that returned string into my python code so that I can actually print out what the specific error is and not simply a 405.
I am trying to parse a response.text that I get when I make a request using the Python Requests library. For example:
def check_user(self):
method = 'POST'
url = 'http://localhost:5000/login'
ck = cookielib.CookieJar()
self.response = requests.request(method,url,data='username=test1&passwd=pass1', cookies=ck)
print self.response.text
When I execute this method, the output is:
{"request":"POST /login","result":"success"}
I would like to check whether "result" equals "success", ignoring whatever comes before.
The manual suggests: if self.response.status_code == requests.codes.ok:
If that doesn't work:
if json.loads(self.response.text)['result'] == 'success':
whatever()
Since the output, response, appears to be a dictionary, you should be able to do
result = self.response.json().get('result')
print(result)
and have it print
'success'
If the response is in json you could do something like (python3):
import json
import requests as reqs
# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
To see everything in the response you can use .__dict__:
print(response.__dict__)
import json
def check_user(self):
method = 'POST'
url = 'http://localhost:5000/login'
ck = cookielib.CookieJar()
response = requests.request(method,url,data='username=test1&passwd=pass1', cookies=ck)
#this line converts the response to a python dict which can then be parsed easily
response_native = json.loads(response.text)
return self.response_native.get('result') == 'success'
I found another solution. It is not necessary to use json module. You can create a dict using dict = eval(whatever) and return, in example, dict["result"]. I think it is more elegant. However, the other solutions also work and are correct
Put in the return of your method like this:
return self.response.json()
If you wanna looking for more details, click this following link:
https://www.w3schools.com/python/ref_requests_response.asp
and search for json() method.
Here is an code example:
import requests
url = 'https://www.w3schools.com/python/demopage.js'
x = requests.get(url)
print(x.json())
In some cases, maybe the response would be as expected. So It'd be great if we can built a mechanism to catch and log the exception.
import requests
import sys
url = "https://stackoverflow.com/questions/26106702/how-do-i-parse-a-json-response-from-python-requests"
response = requests.get(url)
try:
json_data = response.json()
except ValueError as exc:
print(f"Exception: {exc}")
# to find out why you have got this exception, you can see the response content and header
print(str(response.content))
print(str(response.headers))
print(sys.exc_info())
else:
if json_data.get('result') == "success":
# do whatever you want
pass