You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo10开发:如何通过全API让REST GET方法返回JSON?

解决Odoo 10 REST GET API正确返回JSON格式的问题

你遇到的核心问题是:直接返回JSON字符串时,Odoo默认会把响应的Content-Type设为text/html,导致Postman无法识别为JSON格式。要解决这个问题,你需要显式构造带有正确响应头的HTTP响应,下面是两种可靠的实现方式:

方法一:使用make_response构造响应

Odoo的http模块提供了make_response函数,可以帮你轻松设置响应头。首先确保导入必要的模块,然后修改你的代码:

import json
from odoo.http import http, make_response

class YourController(http.Controller):  # 记得要继承http.Controller类
    @http.route("/check_method_get", auth='none', type='http', method=['GET'])
    def check_method_get(self, **values):
        output = {
            'results': {
                'code': 200,
                'message': 'OK'
            }
        }
        # 将Python字典转为JSON字符串
        json_response = json.dumps(output)
        # 构造响应并指定Content-Type为application/json
        return make_response(json_response, headers=[('Content-Type', 'application/json; charset=utf-8')])

方法二:使用Response类直接构建响应

另一种方式是使用Odoo的Response类,它能更灵活地控制响应的状态码、编码等属性:

import json
from odoo.http import http, Response

class YourController(http.Controller):
    @http.route("/check_method_get", auth='none', type='http', method=['GET'])
    def check_method_get(self, **values):
        output = {
            'results': {
                'code': 200,
                'message': 'OK'
            }
        }
        return Response(
            response=json.dumps(output),
            content_type='application/json; charset=utf-8',
            status=200
        )

关键说明

  • 不要使用type='json':这个参数是用于处理POST请求的JSON payload的,GET方法的参数通过URL传递,所以保持type='http'即可。
  • 显式设置编码:在Content-Type里加上charset=utf-8可以避免中文等特殊字符出现乱码问题。

这样修改后,Postman就能正确识别响应为JSON格式,响应头的Content-Type也会显示为application/json; charset=utf-8了。

内容的提问来源于stack exchange,提问作者Yuniar Kurniawan S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:49:01