Monday, 8 May 2017

Write web services using Odoo controllers




In Odoo you can write web-services for the outside world. Let's discuss how it can be done using controllers.

Suppose I need a cross-domain API that will return data in JSON format. For that, we have to enable CORS and have to setup nginx reverse proxy.


Example: API to send teachers data from Odoo:

# -*- coding: utf-8 -*-
from odoo.tools.translate import _
from odoo import http
from odoo.http import request
import json
import sys

class odoo_public_data(http.Controller):
    @http.route('/get/teachers', type='http', methods=['GET'], auth="public")

    def get_teachers(self, **kwargs):
        teacher_model = request.env['dps.teacher']
        teacher_ids = teacher_model.sudo().search([])
        teacher_list = {'status': 1, 'data': []}
        try:
            if teacher_ids:
                for teacher in teacher_ids:
                    vals = {
                        'id': teacher.id,
                        'name': teacher.name,
                        'email': teacher.email,
                        'phone': teacher.phone,
                        'school': teacher.partner_id.name,
                    }
                    teacher_list['data'].append(vals)
            return json.dumps(teacher_list)
        except Exception as e:
            print str(e)
            return json.dumps({'status': 0, 'data': 'Some problem with API'})


Please set reverse proxy using tutorial if it's not already set. After that add lines from the link(https://enable-cors.org/server_nginx.html) in the location block, to enable CORS, of a virtual host config file.

Thanks!!!!! Enjoy Programming!!! :)

1 comment:

  1. Pouvez-vous montrer comment on réalise une authentification? C'est "post" à ce que je crois

    ReplyDelete

Thanks for your valuable comments.

Nginx: Cannot allocate memory