Send json data for json get request in odoo 12 - json

I want send json data from odoo controller.For that i have created below controller
from odoo.http import Response
import json
#http.route('/api/json_get_request',auth='public',type='json',methods=["GET"],csrf=False)
def printjson(self,**kw):
headers={'content-type':'application/json'}
return Response(json.dumps({"test":"json string"}),headers=headers)
but accessing http://localhost:8089/api/json_get_request in postman gives me Invalid json data then I have check postman console in that response header -> Content-Type: "text/html" is shown.
Not understand after sending data in the json type why json data not recieved.
After accessing http://localhost:8089/api/json_get_request as http request on postman gives me correct json data.
Please give me suggestion
Thanks in advance

First thing method that handle 'json' request should return a dictionary directly:
#http.route('/api/json_get_request', auth='public', type='json', csrf=False)
def printjson(self, **kw):
return {'attribute': 'test'}
this will return a result like this:
{
"jsonrpc": "2.0",
"id": null,
"result": {
"attribute": "test"
}
}
You are having this error because you didn't send any json data with the request.
You could test your code using the requests module:
>>> import requests
>>> import json
>>> url = 'http://localhost:8069/api/json_get_request'
>>> data = {'params': {'test': 100}}
>>> headers={'content-type':'application/json'}
>>> requests.get(url, data=json.dumps(data), headers=headers)
<Response [404]>
It gives me this error because there is no database selected, and I have more than one database.
If you have only one database you see the correct result.
but when you test it from Postman extension I used RESTED
Because I'm all ready logged to Odoo the method was executed successfully , Just look for a better postman extension or search how to send json data with your current postman. You need to send some json data in the request.

Related

Azure Message Routing: JSON message in wrong format

I'm working with a raspberry pi zero and Python to send and recieve sensor data with Azure IoT. I've already created an endpoint and message routing to the storage container. But when I check the JSON-Files in the container, I've got two problems:
The file include various general data which i don't need
My message body is in Base24-format
My message looks like this:
{"EnqueuedTimeUtc":"2021-06-25T13:03:25.7110000Z","Properties":{},"SystemProperties":{"connectionDeviceId":"RaspberryPi","connectionAuthMethod":"{"scope":"device","type":"sas","issuer":"iothub","acceptingIpFilterRule":null}","connectionDeviceGenerationId":"637555519600003402","enqueuedTime":"2021-06-25T13:03:25.7110000Z"},"Body":"eyJ0ZW1wZXJhdHVyZSI6IDI4Ljk1LCAicHJlc3N1cmUiOiA5ODEuMDg2Njk1NDU5MzMyNiwgImh1bWlkaXR5IjogNDYuMjE0ODE3NjkyOTEyODgsICJ0aW1lIjogIjIwMjEtMDYtMjUgMTQ6MDM6MjUuNjMxNzk1In0="}
The body included my sensor data in Base64-format. I've already read about contentType = application/JSON and contentEncoding = UTF-8 so that Azure can work with correct JSON files. But where do i apply these settings? When I apply it to the routing query, I get the following error:
Routing Query Error (The server didn't understand your query. Check your query syntax and try again)
I just want to get the body-message in correct JSON Format.
Thank you all for any kind of help! Since it's my first experience with this kind of stuff, I'm a little helpless.
Zero clue if this helps, but here is my code for sending data from Raspberry Pi Python to AWS - Parse Server using base64/JSON. The only reason I use base64 is to send pictures. You should only have to use JSON to send your other data.
import requests
import random, time
import math
import json
import Adafruit_DHT
import base64
from Adafruit_CCS811 import Adafruit_CCS811
from picamera import PiCamera
from time import sleep
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN =4
ccs = Adafruit_CCS811()
camera = PiCamera()
while True:
time.sleep(5)
camera.start_preview()
sleep(5)
camera.capture('/home/pi/Desktop/image.jpg')
camera.stop_preview()
with open('/home/pi/Desktop/image.jpg', 'rb') as binary_file:
binary_file_data = binary_file.read()
base64_encoded_data = base64.b64encode(binary_file_data)
base64_message = base64_encoded_data.decode('utf-8')
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
ccs.readData()
parseServer = {
"temp": temperature,
"humid": humidity,
"co2": ccs.geteCO2(),
"pic": base64_message
}
resultJSON = json.dumps(parseServer)
headers = {
'X-Parse-Application-Id': 'myappID',
'Content-Type': 'application/json',
}
data = resultJSON
response =
requests.put('http://1.11.111.1111/parse/classes/Gamefuck/TIuRnws3Ag',
headers=headers, data=data)
print(data)
If you're using the Python SDK for Azure IoT, sending the message as UTF-8 encoded JSON is as easy as setting two properties on your message object. There is a good example here
msg.content_encoding = "utf-8"
msg.content_type = "application/json"
Furthermore, you don't need to change anything in IoT Hub for this. This message setting is a prerequisite to be able to do message routing based on the body of the message.

Extract data from Zapier Storage

I was successful in publishing (POST) a JSON file in Zapier and creating a Storage for it. However, I´d like to access the JSON in Zapier Storage using a Python code run locally. I am able to access the storage with Python3, see that is something written there, but I cannot access the JSON contents.
import urllib
import json
import codecs
reader = codecs.getreader("utf-8")
access_token = "password"
def GetStorage(page_id, access_token):
url = 'https://hooks.zapier.com/url/'
response = urllib.request.urlopen(url)
data = json.load(reader(response))
return data
a=GetStorage(url, access_token)
print(a)
All I get is:
{'attempt': '5a539a49-65eb-44f8-a30e-e171faf7a680',
'id': '1b38d21a-0150-46df-98c1-490a0d04b565',
'request_id': '5a539a49-65eb-44f8-a30e-e171faf7a680',
'status': 'success'}
When in fact I need:
{'Name':'value',
'Address': 'value'
}
Any ideas ?
David here, from the Zapier Platform team.
You're close! hooks.zapier.com is the url we use for incoming webhooks, so we always reply with a 200 and the response body you're seeing.
Instead, use store.zapier.com. You'll also want to make sure to include your secret. A full request URL will look like:
https://store.zapier.com/api/records?secret=test
which will return arbitrary json data:
{
"name": "david",
"job": "programmer"
}
The full docs are in json here: https://store.zapier.com/

Call an API with python

I used Postman to get a bit more info and have used the snippet of code to run the request it is working now but i still want the request to print in JSON not in text im really stuck.....
import requests
url = "https://ice3x.com/api/v1/stats/marketdepthfull/"
headers = {
'cache-control': "no-cache",
'postman-token': "afb97efe-aaf1-cdae-004f-29aac565780a"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
The result i get is:-
{"errors":false,"response":{"entities":[{"pair_id":"3","min":"56600.00000000","max":"59600.00000000","avg":"58547.48550813","vol":"5.68526617","pair_name":"btc/zar","last_price":"58547.00000000"},{"pair_id":"4","min":"0.00000000","max":"0.00000000","avg":"0.00000000","vol":"0.00000000","pair_name":"btc/ngn","last_price":"1560000.00000000"},{"pair_id":"6","min":"732.00000000","max":"781.00000000","avg":"765.97099358","vol":"160.77519562","pair_name":"ltc/zar","last_price":"760.00000000"},{"pair_id":"11","min":"4050.00000000","max":"4349.00000000","avg":"4253.33493584","vol":"74.22964491","pair_name":"eth/zar","last_price":"4230.00000000"},{"pair_id":"12","min":"0.00000000","max":"0.00000000","avg":"0.00000000","vol":"0.00000000","pair_name":"eth/ngn","last_price":"110000.00000000"}]},"pagination":{"items_per_page":1000,"total_items":5,"current_page":1,"total_pages":1}}
Process finished with exit code 0
What i need is to be able to dump the json and call it again if i need it
Please help

Want to receive json response for GET request. Postman gives me the json data. But when I do it programatically it returns empty html

import requests
import json
#Infrastructure API URL
url = "http://10.39.188.69/server-manager/tomcat/bimws/rest/v1/infrastructures/?format=json"
myResponse = requests.get(url, headers=headers, verify=False)
print myResponse
print(myResponse.status_code)
#print(myResponse.text)
print(myResponse.json)
Output i get:
c:\automation>python rest_API.py
C:\Python27\lib\site-
packages\requests\packages\urllib3\connectionpool.py:852:
nsecureRequestWarning: Unverified HTTPS request is being made. Adding
certificate verification is strongly advised. See:
https://urllib3.readthedocs.io/en/late/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py:852:
nsecureRequestWarning: Unverified HTTPS request is being made. Adding certifica
e verification is strongly advised. See: https://urllib3.readthedocs.io/en/late
t/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
<Response [200]>
<bound method Response.json of <Response [200]>>
Try doing myResponse.json(). myResponse.json returns an instancemethod type while myResponse.json() will return the json data.

OpenERP #http.route('demo_json', type="json") URL not displaying JSON Data

I am create controller in OpenERP Framework. Following is my code and i set http.route type="http",
import openerp.http as http
from openerp.http import request
class MyController(http.Controller):
#http.route('demo_html', type="http")
def some_html(self):
return "<h1>This is a test</h1>"
Above code work perfect once i login into openerp after i modify URL http://localhost:8069/demo_html show me return result This is a test in h1 heading tag.
But same way i try to type="json" and add following json code and again try to call URL http://localhost:8069/demo_json Its not work properly and show me error "Internal Server Error".
import openerp.http as http
from openerp.http import request
class MyController(http.Controller):
#http.route('demo_html', type="http") // Work Pefrect when I call this URL
def some_html(self):
return "<h1>This is a test</h1>"
#http.route('demo_json', type="json") // Not working when I call this URL
def some_json(self):
return {"sample_dictionary": "This is a sample JSON dictionary"}
So my question is how to route json. Any help would be appreciate Thank you.
This is because there is difference between type="json" and type="http".
type="json":
it will call JSONRPC as an argument to http.route() so here , there will be only JSON data be able to pass via JSONRPC, It will only accept json data object as argument.
type="http":
As compred to JSON, http will pass http request arguments to http.route() not json data.
I think , you need to do some extra stuff while working with type="json",you have to trigger that method using json rpc from js.
like :
$(document).ready(function () {
openerp.jsonRpc("demo_json", 'call', {})
.then(function (data) {
$('body').append(data[0]);
});
return;
})
and yes do not forget to return your dictionary in list like
#http.route('demo_json', type="json")
def some_json(self):
return [{"sample_dictionary": "This is a sample JSON dictionary"}]