southernegro
southernegro

Reputation: 394

How to call Odoo data from JSON controller?

So I need to make a Rest service which will call data from an specific model.

In order to do this, I must create a controller.

I'm newbie with Odoo, also with Json, and I can't find anything that could work for this.

Far I have is all I need but in a http request.

class RestService(http.Controller):
    @http.route('/orders/<model("sale.order"):order>', auth='none', website=True)
    def consulta_orden(self , order):
        return request.render('consulta_pedidos.order', {'order': order})
        
        return {'order_id': order_id}

The idea is that when I hace the data loaded, I can render this data in a template. Already did this with an Http request, but I need it with Json. Any tip about how to implement it better.

Upvotes: 0

Views: 2970

Answers (2)

southernegro
southernegro

Reputation: 394

I solved my problem in a very simple way.

The code:

@http.route(['/orden_detalle', '/orden_detalle/<int:order_id>'], type='json', auth='user')
    def orden_detalle(self, order_id=None):
        if order_id:
            domain = [('id', '=', order_id)]
        else:
            domain = []
        sales_rec = request.env['sale.order'].search(domain)
        sales = []
        for rec in sales_rec:
            vals = {
                'id': rec.id,
                'name': rec.name,
                'partner_id': rec.partner_id.name,
                'user_id': rec.user_id.name,
            }
            sales.append(vals)
        data = {'status': 200, 'response': sales, 'message': 'Sale(s) returned'}
        return data

My source:

  1. https://www.youtube.com/watch?v=wGvuRbCyytk
  2. Another of my questions: How to get specific record in json controller in Odoo 12

Upvotes: 2

Jeroen Evens
Jeroen Evens

Reputation: 125

If you want to return Json (for a REST-API) you just need to return it in a Response object.

Make sure you have Response imported from odoo.http. Then you can return the json data like this:

return Response(json.dumps({'order_id': order_id}), status=200, content_type="application/json")

I usually wrap this logic in a separate function (outside of the controller) that logs the request and response on the Odoo object that is updated, and then returns the Response object. That way it can also be easily reused in Error handling (where you can then return a custom error response in Json format)

EDIT: also make sure you're not including Content-Type: application/json in the request, in that case Odoo will think it's a JSON-RPC request.

Upvotes: 0

Related Questions