Show Json Data from Python - python

How do i make Json requests to an endpoint to show the response in Json rather than show the response
i sent a POST request to a server and i am getting this as response.
D:\python>python runVacc.py
<Response [200]>
Which means its a successful request, but i want it to show both the Success as well as the Json Response. My Code is looking thus :
import requests
import json
url = 'URL HERE'
data = {"email":"tim#john.com","is_permanent":True,"bvn":"12345678901","tx_ref":"VAL12","phonenumber":"08098688235","firstname":"John","lastname":"Fish","narration":"Test ACC"}
res = requests.post(url, data=json.dumps(data),headers={'Content-Type':'application/json','Authorization':'Bearer FLWSECK_TEST-2033696a107e162088cdb02f777fa44e-X'})
print(res)
How do I make it to print Json Response containing the Json Data?
Please help, I am new to this.

Use print(res.content) instead.

Related

How to pass JSON to REST API (IBKR)

I am using json and urllib to pull data from the IBKR client portal API:
data = json.load(urlopen("https://localhost:5000/v1/api/portfolio/{acct ID}/positions"
I am having trouble understanding how to pass information to it, for example, to place orders. The documentation just says "pass json here" basically and gives the url: /server/account/{accountId}/orders.
There are no other instructions in the documents.
I would imagine the API is expecting a POST request containing a JSON object in the body of the request.
Using the requests library (pip install requests)...
r = requests.post('.....server/account/{accountId}/orders', json={"key": "value"})
r is the response from that POST request.
You can then do these to view the response from the server and figure out if you are posting valid data:
r.status_code
r.json()

Clarification on POST multipart request with python requests and urllib2

I am trying to submit a multipart POST request in Python. I looked around and found 2 variations:
Using 'reqests' (http://docs.python-requests.org/en/latest/)
Using urllib2 (https://docs.python.org/2/library/urllib2.html#module-urllib2)
I tried both of them and am able to submit the request successfully.
Below is the sample code for both:
----------requests--------------
resp = requests.post(submiturl, files=multipart_form_data, headers=headers,timeout=5)
where multipart_form_data contains my file object as well as string parameters
---------------urllib2------------
items.append(MultipartParam(name, value))
fileObj = open(inputFile,'r')
items.append(MultipartParam('file', filename=inputFile, fileobj=fileObj))
res = urllib2.urlopen(request)
My Question:
Which one should I use?
Correct me if I am wrong but I have seen that while submitting with urllib2 I get the HTTPError for response code like 500. However, while using "request" it does not throw the HTTPError for response code like 500s instead I have to manually add the condition:
Response.raise_for_status():
or:
resp.status_code != 200: raise Execption(...)
Is this correct or I am missing something?
Thanks!
Response.raise_for_status() raises for HTTP response code in the 4xx and 5xx ranges. The src is very clear and readable.
You'll get a 2xx response for successful requests, but you may also want to consider other response codes, for example redirects.

Python Parse JSON Response from URL

I'm am wanting to get information about my Hue lights using a python program. I am ok with sorting the information once I get it, but I am struggling to load in the JSON info. It is sent as a JSON response. My code is as follows:
import requests
import json
response= requests.get('http://192.168.1.102/api/F5La7UpN6XueJZUts1QdyBBbIU8dEvaT1EZs1Ut0/lights')
data = json.load(response)
print(data)
When this is run, all I get is the error:
in load return loads(fp.read(),
Response' object has no attribute 'read'
The problem is you are passing in the actual response which consists of more than just the content. You need to pull the content out of the response:
import requests
r = requests.get('https://github.com/timeline.json')
print r.text
# The Requests library also comes with a built-in JSON decoder,
# just in case you have to deal with JSON data
import requests
r = requests.get('https://github.com/timeline.json')
print r.json
http://www.pythonforbeginners.com/requests/using-requests-in-python
Looks like it will parse the JSON for you already...
Use response.content to access response content and json.loads method instead of json.load:
data = json.loads(response.content)
print data

POST JSON with python and reading response

I am trying to make a post request in python and I believe I am doing everything correct. However it is not returning any response. I can't seem to figure out if there is anything wrong with my request. It seems like there may be something wrong with the service if I am not getting any response back. Is there anything inherently wrong with what I've written here?
import json
import urllib2
data = {'first_name': 'John','last_name': 'Smith','email': 'johnsmith#smith.com','phone': '215-555-1212'}
req = urllib2.Request('https://someurl.io/')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
print response.read()
print response.headers
Honestly, unless you love urllib2, I suggest using requests. Here's the same data code in requests:
import requests
import json
payload = {'first_name': 'John','last_name': 'Smith','email': 'johnsmith#smith.com','phone': '215-555-1212'}
url = 'https://someurl.io/'
r = requests.post(url, json=json.dumps(payload))
print r.content
print r.headers

python-oauth2 - issue Request objects

Via the tutorial at https://github.com/simplegeo/python-oauth2, I can create a signed Request object. But I don't understand how to send the request and receive anything back.
When I check the URL that I get from request.to_url(), I get a response. I just don't know how to get it programmatically.
To make a GET request, you can just do
import urllib2
response = urllib2.urlopen(request.to_url())
response_body = response.read() # in case you need it
For POST, you should be able to do
import urllib2
urllib2_req = urllib2.Request(request.url, request.to_postdata())
response = urllib2.urlopen(urllib2_req)
response_body = response.read() # in case you need it

Categories