Yuniar Kurniawan S
Yuniar Kurniawan S

Reputation: 93

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.

Upvotes: 3

Views: 5720

Answers (2)

sennhvi
sennhvi

Reputation: 21

import json
from odoo import http
from odoo.http import request, Response, JsonRequest

from odoo.tools import date_utils


class OdooAPI(http.Controller):
    def alternative_json_response(self, result=None, error=None):

        if error is not None:
            response = error

        if result is not None:
            response = result

        mime = 'application/json'

        body = json.dumps(response, default=date_utils.json_default)

        return Response(

            body, status=error and error.pop('http_status', 200) or 200,

            headers=[('Content-Type', mime), ('Content-Length', len(body))]

        )

    # ...

    @http.route('/api/auth/', type="json", auth="none", methods=["POST"], csrf=False)
    def get_session(self, *args, **kwargs):
        # your auth code here
        data = {
            "result": "data info",
            "status": 200,
            "info": "success"
        }
        request._json_response = self.alternative_json_response.__get__(request, JsonRequest)
        return data

Upvotes: 2

Phillip Stack
Phillip Stack

Reputation: 3378

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)

Upvotes: 4

Related Questions