Skip to Content
Menu
This question has been flagged
2 Replies
10708 Views

I need to make a custom controller on Odoo for getting information from the particular task. And I can able to produce the result also. But now I'm facing an issue.

The client needs to retrieve the information with a particular field.

For example, The client needs to retrieve the information with the tracking number and the data must be JSON format also. If the tracking number is 15556456356, the URL should be www.customurl.com/dataset/15556456356


Avatar
Discard
Author Best Answer

Found answer by myself:


The route of that URL should be @http.route('/dataset/<string:tracking_number>', type='http or json', auth="user or public"), basically the method should be like this:


import json

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

class tracking(http.Controller):
    # if user must be authenticated use auth="user"
    @http.route('/dataset/<string:tracking_number>', type='http', auth="public")
    def tracking(self, tracking_number):  # use the same variable name
        result = # compute the result with the given tracking_number and the result should be a dict to pass it json.dumps
        return Response(json.dumps(result), content_type='application/json;charset=utf-8',status=200)



This method accept http request and return a json response, if the client is sending a json requests you should change type='json'. don't forget to import the file in the __init___.py.

Lets take an example let say that I want to return some information about a sale.order by a giving ID in the URL:



import json

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

 class Tracking(http.Controller):
    @http.route('/dataset/<int:sale_id>', type='http', auth="public")
    def tracking(self, sale_id):
        # get the information using the SUPER USER
        result = request.env['sale.order'].sudo().browse([sale_id]).read(['name', 'date_order'])
        return Response(json.dumps(result), content_type='application/json;charset=utf-8',status=200)

So when I enter this URL using my Browser: http://localhost:8069/dataset/1:




Avatar
Discard
Best Answer

Taking a look at how other controllers in Odoo work is the easiest way to understand how to set one up.

URL routing is based on Werkzeug Route Expressions. This means you can use angled brackets to add variables to the url, eg. '/dataset/<string:tracking_number>'. This will be passed into your controller function by name, so make sure you include tracking_number as a parameter.

Avatar
Discard
Related Posts Replies Views Activity
3
Jun 24
23122
2
Dec 24
6738
2
Nov 24
27081
2
May 24
6525
3
Mar 24
5872