How to get the result from API not only the response code - python-3.x

I am trying to get the result of foreign currency exchange rate but on sending a Get request to the API "https://data.fixer.io/api/".." instead of getting a result, I am getting a response code 200 but no exchange rates are there
def main():
res=requests.get("http://data.fixer.io/api/latest? access_key = YOUR_ACCESS_KEY& base = INR& symbols = USD")
if res.status_code!=200:
raise Exception("Error : APIdidn't work")
print(res)
Expected result:
{
"success":true,
"timestamp":1559223544,
"base":"INR",
"rates":{
"USD":0.014,
}
}
Actual result :
<Response [200]>

To use the data that you're pulling from the API - you need to convert it to readable json. DeepSpace is correct - you need to use res.json()
Append the data to a variable if you want to iterate through it or utilize it further.
data = res.json()

Related

How to set response status code in route with type json in odoo 14

I have created a route with type Json in odoo 14.
#http.route('/test', auth='public', methods=['POST'], type="json", csrf=False)
def recieve_data(self, **kw):
headers = request.httprequest.headers
args = request.httprequest.args
data = request.jsonrequest
So when I receive request using this route everything is fine, but suppose I want to return a different status code like 401, I could not do that with the route which type is json.
I have also tried the bellow method but the problem with this method is that it stops all odoo future requests.
from odoo.http import request, Response
#http.route('/test', auth='public', methods=['POST'], type="json", csrf=False)
def recieve_data(self, **kw):
headers = request.httprequest.headers
args = request.httprequest.args
data = request.jsonrequest
Response.status = "401 unauthorized"
return {'error' : 'You are not allowed to access the resource'}
So in the above example If I set the response status code to 401 all other requests even if they are to different routes will be stopped and its status code changes 401 .
I have checked this problem in both odoo14 and odoo13.
You cannot specify the code of the response, as you can see the status code is hardcoded in http.py:
def _json_response(self, result=None, error=None):
# ......
# ......
return Response(
body, status=error and error.pop('http_status', 200) or 200,
headers=[('Content-Type', mime), ('Content-Length', len(body))]
)
If the result is not an error the status code is always 200. but you can change the code of the method directly or use a monkey patch witch if it's not really important to specify the code of status in the result don't do ti ^^.
A simple monkey patch put this in __init__.py of the module that you want this behavior in it.
from odoo.http import JsonRequest
class JsonRequestPatch(JsonRequest):
def _json_response(self, result=None, error=None):
response = {
'jsonrpc': '2.0',
'id': self.jsonrequest.get('id')
}
default_code = 200
if error is not None:
response['error'] = error
if result is not None:
response['result'] = result
# you don't want to remove some key of another result by mistake
if isinstance(response, dict)
defautl_code = response.pop('very_very_rare_key_here', default_code)
mime = 'application/json'
body = json.dumps(response, default=date_utils.json_default)
return Response(
body, status=error and error.pop('http_status', defautl_code ) or defautl_code,
headers=[('Content-Type', mime), ('Content-Length', len(body))]
)
JsonRequest._json_response = JsonRequestPatch._json_response
and in the result of JSON api you can change the code of status like this
def some_controler(self, **kwargs):
result = ......
result['very_very_rare_key_here'] = 401
return result
The risk in monkey patching is you override the method compeletly and if some change is done in Odoo in new version you have to do you it in your method too.
The above code is from odoo 13.0 I did a lot of this when I build a restfull module to work with a website uses axios witch don't allow sending body in GET request. and odoo expect the argument to be inside the body in json request.

Python3 Request from API return Not Found

I am trying to get a balance from some address at a explorer on Python but I get 404 error and I believe that is related to a list.
This is my code:
import urllib.request, json, requests
listAddress = [
"HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf"
]
explorerUrl = 'http://explorer.htmlcoin.com'
urlBase = '/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/'
balance = '/balance'
for address in listAddress:
urlGamb = explorerUrl+urlBase+address+balance
json_data = urlGamb
r = requests.post(json_data)
r.status_code
r.json()
print(r.json())
The problem is that returns this error:
python3 newwork.py
{'status': 404, 'url': '/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf/balance', 'error': 'Not found'}
So, what am I doing wrong here?
Minor suggestion:
urlGamb = f"{explorerUrl}{urlBase}{address}{balance}"
I don't know about the API, you did not provide a link, but the value of urlGamb is 'http://explorer.htmlcoin.com/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf/balance' and that is not JSON. The assignment to json_data seems like a conceptual error because the URL string is not json. If the post requires a JSON payload then the docs should tell you how to construct it.
Should the post have been a get request instead? That would make sense because according to REST standards, post is for changing state on the server, and you are only making a query.

You cannot access body after reading from request's data stream, django

I am trying to read request body using django but, it throws an error:
You cannot access body after reading from request's data stream
Here is my code:
#csrf_exempt
def update_profile(request):
"""
"""
if request.method == 'POST':
try:
# Validate
payload = json.loads(request.body)
# get files
profile_pic = request.FILES.get('profile_pic')
user_data = util.update_profile(obj_common, user_id, payload,profile_pic)
return user_data
I have seen many answer on the stackoverflow, They advice me to replace request.body with request.data.
but when it tried i got another error
{AttributeError}'WSGIRequest' object has no attribute 'data'
Looks like request.POST is being processed somewhere before calling this function. Try searching for it

Get Facebook Marketing API Ads insights results as CSV or JSON format

I am attempting to use the Facebook-Python-Ads-SDK to automate reporting on Ad Account performance. I have successfully requested a report at the ad set level, however the output of the report is a Cursor object, where I would prefer it to be a json or csv. I have tried the "export_format" option in params but it does not seem to make any difference. The output looks like JSON, so I attempted to import the object as a dataframe in pandas using pd.read_json(result) but it gives off an error saying that the object type "Cursor" needs to be str or bytes.
Does anyone have any experience with this api that can help me out? My code is below.
def report_request(start_date,end_date):
fields = [
'date_start',
'account_name',
'adset_name',
'ad_name',
'impressions',
'clicks',
'spend'
]
params = {
'time_range': {
'since': start_time,
'until': end_time,
},
'level':'ad',
'export_format':'csv'
}
account_id = [<ACCOUNT_ID>]
adAccount = AdAccount('act_' + account_id)
api_batch = get_api().new_batch()
request = adAccount.get_insights(fields=fields, params=params, async=False, batch=api_batch)
result = request.execute()
return result

Can't extract data from RESTClient response

I am writing my first Groovy script, where I am calling a REST API.
I have the following call:
def client = new RESTClient( 'http://myServer:9000/api/resources/?format=json' )
That returns:
[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]
I am trying to get the field level, like this:
def level_value = client.get( path : 'msr/data/level' )
However, when I print the value of the variable obtained:
println level_value.getData()
I get the whole JSON object instead of the field:
[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]
So, what am I doing wrong?
Haven't looked at the docs for RESTClient but like Tim notes you seem to have a bit of a confusion around the rest client instance vs the respons object vs the json data. Something along the lines of:
def client = new RESTClient('http://myServer:9000/api/resources/?format=json')
def response = client.get(path: 'msr/data/level')
def level = response.data[0].msr[0].data.level
might get you your value. The main point here is that client is an instance of RESTClient, response is a response object representing the http response from the server, and response.data contains the parsed json payload in the response.
You would need to experiment with the expression on the last line to pull out the 'level' value.

Resources