How to get JSON data in an Odoo controller using type='json'?

跟風遠走 提交于 2019-12-05 07:45:52
Prakash Kumar

You have just forgotten to put your data inside the params keywords:

Use this correct syntax :

data = {"params": dict(key="value")}

data = {
    "params": {
        "name":"prakashsharma",
        "email":"prakashsharmacs24@gmail.com",
        "phone":"+917859884833"
    }
}

Please don't forget to use json.dumps(data) and 'Content-Type': 'application/json' while requesting a resource in json format.

I am damn sure your issue will be solved after using this one my friend... cheers :)!!

God Bless Forvas:: But for more clearity: if you want to test through cURL:

curl -i -X POST -H "Content-Type: application/json" -d '{"params": {"name":"prakashsharma","email":"prakashsharmacs24@gmail.com","phone":"+917859884833"}}' 'http://localhost:8069/web/yourlistoner/'

if you want to test through python request:

import requests

headers = {
    'Content-Type': 'application/json',
}

data = '{"params": {"name":"prakashsharma","email":"prakashsharmacs24@gmail.com","phone":"+917859884833"}}'

requests.post('http://localhost:8069/web/yourlistoner/', headers=headers, data=data)

the function in odoo will be something like

from odoo import http
import json

class YourClass(http.Controller):
    @http.route('/web/yourlistoner/', type='json', auth="none", methods=['POST'],cors="*", csrf=False)
    def listoner(self, **kw):

        print http.request.params
        print "lllllllllllllllllllll"
        return json.dumps({"result":"Success"}) 

You can use below format for a POST request

{
"params" : {
    "name" : "Order/1/18",
    "session_id" : 1,
    "customer_count" : 2,
    "partner_id" : 9,
    "lines": [
        {
            "product_id": 37,
            "qty" : 2,
            "price_unit" : 2,
            "discount" : 10
        }
        ],
    "pos_reference" : 2,
    "note" : "This is a test note"
}
}

Content type must be application/json

How odoo route will handle request ?

Route will help creating a POS order in odoo [POST]

@http.route(['/api/v1/resources/<string:api_key>/pos_order'], 
            auth="public",
            website=False,
            type="json",
            csrf=False,
            methods = ['POST'])
def create_update_pos_order(self, api_key=None, **kwargs):
    print(kwargs.get('name')) -> Order/1/18
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!