Search code examples
jsonpython-2.7odoo-10webservices-client

How to return JSON in REST get method using the Odoo full API


I made an api with 'GET' method in odoo10 and I would like the return value is in json. When I run my code below with postman

@http.route("/check_method_get", auth='none', type='http',method=['GET'])
def check_method_get(self,**values):
    output = {
        'results':{
            'code':200,
            'message':'OK'
        }
    }

    return json.dumps(output)

the result in Headers is

Content-Length →43
Content-Type →text/html; charset=utf-8
Date →Mon, 30 Apr 2018 15:07:30 GMT
Server →Werkzeug/0.11.11 Python/2.7.12
Set-Cookie →session_id=505500f3f5b83ada1608d84e38d2f1776006b443;  Expires=Sun, 29-Jul-2018 15:07:30 GMT; Max-Age=7776000; Path=/ 

and the result in Body is

{"results": {"message": "OK", "code": 200}}

The problem is that Content-Type →text/html. I want the Content-Type →application/json. Then I change my code below

@http.route("/check_method_get", auth='none', type='http',method=['GET'])
def check_method_get(self,**values):
    return Response(headers={
            'Content-Type': 'application/json',
            'results':{
                'code':200,
                'message':'OK'
            }
        })

The result in Header is

Content-Length →0
Content-Type →application/json
Date →Mon, 30 Apr 2018 15:18:41 GMT
Server →Werkzeug/0.11.11 Python/2.7.12
Set-Cookie →session_id=505500f3f5b83ada1608d84e38d2f1776006b443;   Expires=Sun, 29-Jul-2018 15:18:41 GMT; Max-Age=7776000; Path=/
results →{'message': 'OK', 'code': 200}

But there is no result in Body. I want {"results": {"message": "OK", "code": 200}} in Body Result as json.

Is there any clue to fix the problem, as long as I have been searching for that the return value in JSON only in 'POST' method.


Solution

  • The issue I think is related to processing which Odoo is running on the response. Because you specify type='http' Odoo adds the appropriate headers for a simple http request and not 'application/json'.

    Try this

    @http.route("/check_method_get", auth='none', type='json',method=['GET'])
    def check_method_get(self,**values):
        output = {
            'results':{
                'code':200,
                'message':'OK'
            }
        }
    return json.dumps(output)
    

    Your other attempt has placed all the content inside the header. You might be able to make it work modifying the request as follows.

    @http.route("/check_method_get", auth='none', type='http',method=['GET'])
    def check_method_get(self,**values):
        headers = {'Content-Type': 'application/json'}
        body = { 'results': { 'code':200, 'message':'OK' } }
    
        return Response(json.dumps(body), headers=headers)