Package: odoo12-addon-base-rest
This addon provides the basis to develop high level REST APIs for Odoo.As Odoo becomes one of the central pieces of enterprise IT systems, it often
becomes necessary to set up specialized service interfaces, so existing
systems can interact with Odoo.While the XML-RPC interface of Odoo comes handy in such situations, it
requires a deep understanding of Odoo’s internal data model. When used
extensively, it creates a strong coupling between Odoo internals and client
systems, therefore increasing maintenance costs.Once developed, anOpenApidocumentation
is generated from the source code and available via aSwagger UIserved by your odoo server
athttps://my_odoo_server/api-docs.Table of contentsConfigurationUsageKnown issues / RoadmapChangelog12.0.2.0.112.0.2.0.012.0.1.0.112.0.1.0.0Bug TrackerCreditsAuthorsContributorsMaintainersConfigurationLoad this module at Odoo startup including in your server config file:server_wide_modules=base,web,base_restIf an error occurs when calling a method of a service (ie missing parameter,
..) the system returns only a general description of the problem without
details. This is done on purpose to ensure maximum opacity on implementation
details and therefore lower security issue.This restriction can be problematic when the services are accessed by an
external system in development. To know the details of an error it is indeed
necessary to have access to the log of the server. It is not always possible
to provide this kind of access. That’s why you can configure the server to run
these services in development mode.To run the REST API in development mode you must add a new section
‘[base_rest]’ with the option ‘dev_mode=True’ in the server config
file.[base_rest]dev_mode=TrueWhen the REST API runs in development mode, the original description and a
stack trace is returned in case of error.Be careful to not use this mode
in production.UsageTo add your own REST service you must provides at least 2 classes.A Component providing the business logic of your service,A Controller to register your service.The business logic of your service must be implemented into a component
(odoo.addons.component.core.Component) that inherit from
‘base.rest.service’Initially, base_rest expose by default all public methods defined in a service.
The conventions for accessing methods via HTTP were as follows:The methoddef get(self, _id)if defined, is accessible via HTTP GET routes<string:_service_name>/<int:_id>and<string:_service_name>/<int:_id>/get.The methoddef search(self, **params)if defined, is accessible via the HTTP GET routes<string:_service_name>/and<string:_service_name>/search.The methoddef delete(self, _id)if defined, is accessible via the HTTP DELETE route<string:_service_name>/<int:_id>.Thedef update(self, _id, **params)method, if defined, is accessible via the HTTP PUT route<string:_service_name>/<int:_id>.Other methods are only accessible via HTTP POST routes<string:_service_name>or<string:_service_name>/<string:method_name>or<string:_service_name>/<int:_id>or<string:_service_name>/<int:_id>/<string:method_name>fromodoo.addons.component.coreimportComponentclassPingService(Component):_inherit='base.rest.service'_name='ping.service'_usage='ping'_collection='my_module.services'# The following method are 'public' and can be called from the controller.defget(self,_id,message):return{'response':'Get called with message '+message}defsearch(self,message):return{'response':'Search called search with message '+message}defupdate(self,_id,message):return{'response':'PUT called with message '+message}# pylint:disable=method-required-superdefcreate(self,**params):return{'response':'POST called with message '+params['message']}defdelete(self,_id):return{'response':'DELETE called with id%s'%_id}# Validatordef_validator_search(self):return{'message':{'type':'string'}}# Validatordef_validator_get(self):# no parameters by defaultreturn{}def_validator_update(self):return{'message':{'type':'string'}}def_validator_create(self):return{'message':{'type':'string'}}Once you have implemented your services (ping, …), you must tell to Odoo
how to access to these services. This process is done by implementing a
controller that inherits fromodoo.addons.base_rest.controllers.main.RestControllerfromodoo.addons.base_rest.controllersimportmainclassMyRestController(main.RestController):_root_path='/my_services_api/'_collection_name=my_module.servicesIn your controller, _’root_path’ is used to specify the root of the path to
access to your services and ‘_collection_name’ is the name of the collection
providing the business logic for the requested service/By inheriting fromRestControllerthe following routes will be registered
to access to your services@route([ROOT_PATH+'<string:_service_name>',ROOT_PATH+'<string:_service_name>/search',ROOT_PATH+'<string:_service_name>/<int:_id>',ROOT_PATH+'<string:_service_name>/<int:_id>/get'],methods=['GET'],auth="user",csrf=False)defget(self,_service_name,_id=None,**params):method_name='get'if_idelse'search'returnself._process_method(_service_name,method_name,_id,params)@route([ROOT_PATH+'<string:_service_name>',ROOT_PATH+'<string:_service_name>/<string:method_name>',ROOT_PATH+'<string:_service_name>/<int:_id>',ROOT_PATH+'<string:_service_name>/<int:_id>/<string:method_name>'],methods=['POST'],auth="user",csrf=False)defmodify(self,_service_name,_id=None,method_name=None,**params):ifnotmethod_name:method_name='update'if_idelse'create'ifmethod_name=='get':_logger.error("HTTP POST with method name 'get' is not allowed. ""(service name:%s)",_service_name)raiseBadRequest()returnself._process_method(_service_name,method_name,_id,params)@route([ROOT_PATH+'<string:_service_name>/<int:_id>',],methods=['PUT'],auth="user",csrf=False)defupdate(self,_service_name,_id,**params):returnself._process_method(_service_name,'update',_id,params)@route([ROOT_PATH+'<string:_service_name>/<int:_id>',],methods=['DELETE'],auth="user",csrf=False)defdelete(self,_service_name,_id):returnself._process_method(_service_name,'delete',_id)As result an HTTP GET call to ‘http://my_odoo/my_services_api/ping’ will be
dispatched to the methodPingService.searchIn addition to easily exposing your methods, the module allows you to define
data schemas to which the exchanged data must conform. These schemas are defined
on the basis ofCerberus schemasand associated to the methods using the
following naming convention. For a methodmy_method:def _validator_my_method(self):will be called to get the schema required to
validate the input parameters.def _validator_return_my_method(self):if defined, will be called to get
the schema used to validate the response.In order to offer even more flexibility, a new API has been developed.This new API replaces the implicit approach used to expose a service by the use
of a python decorator to explicitly mark a method as being available via the
REST API:odoo.addons.base_rest.restapi.method.classPartnerNewApiService(Component):_inherit="base.rest.service"_name="partner.new_api.service"_usage="partner"_collection="base.rest.demo.new_api.services"_description="""
        Partner New API Services
        Services developed with the new api provided by base_rest
    """@restapi.method([(["/<int:id>/get","/<int:id>"],"GET")],output_param=restapi.CerberusValidator("_get_partner_schema"),auth="public",)defget(self,_id):return{"name":self.env["res.partner"].browse(_id).name}def_get_partner_schema(self):return{"name":{"type":"string","required":True}}Thanks to this new api, you are now free to specify your own routes but also
to use other object types as parameter or response to your methods.
For example,base_rest_datamodelallows you to use Datamodel object instance
into your services.frommarshmallowimportfieldsfromodoo.addons.base_restimportrestapifromodoo.addons.component.coreimportComponentfromodoo.addons.datamodel.coreimportDatamodelclassPartnerSearchParam(Datamodel):_name="partner.search.param"id=fields.Integer(required=False,allow_none=False)name=fields.String(required=False,allow_none=False)classPartnerShortInfo(Datamodel):_name="partner.short.info"id=fields.Integer(required=True,allow_none=False)name=fields.String(required=True,allow_none=False)classPartnerNewApiService(Component):_inherit="base.rest.service"_name="partner.new_api.service"_usage="partner"_collection="base.rest.demo.new_api.services"_description="""
        Partner New API Services
        Services developed with the new api provided by base_rest
    """@restapi.method([(["/","/search"],"GET")],input_param=restapi.Datamodel("partner.search.param"),output_param=restapi.Datamodel("partner.short.info",is_list=True),auth="public",)defsearch(self,partner_search_param):"""
        Search for partners
        :param partner_search_param: An instance of partner.search.param
        :return: List of partner.short.info
        """domain=[]ifpartner_search_param.name:domain.append(("name","like",partner_search_param.name))ifpartner_search_param.id:domain.append(("id","=",partner_search_param.id))res=[]PartnerShortInfo=self.env.datamodels["partner.short.info"]forpinself.env["res.partner"].search(domain):res.append(PartnerShortInfo(id=p.id,name=p.name))returnresKnown issues / RoadmapTheroadmapandknown issuescan
be found on GitHub.Changelog12.0.2.0.1_validator_…() methods can now return a cerberusValidatorobject
instead of a schema dictionnary, for additional flexibility (e.g. allowing
validator options such asallow_unknown).12.0.2.0.0Licence changed from AGPL-3 to LGPL-312.0.1.0.1Fix issue when rendering the jsonapi documentation if no documentation is
provided on a method part of the REST api.12.0.1.0.0First official version. The addon has been incubated into theShopinvader repositoryfrom
Akretion. For more information you need to look at the git log.Bug TrackerBugs are tracked onGitHub Issues.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us smashing it by providing a detailed and welcomedfeedback.Do not contact contributors directly about support or help with technical issues.CreditsAuthorsACSONE SA/NVContributorsLaurent Mignon <laurent.mignon@acsone.eu>Sébastien Beau <sebastien.beau@akretion.com>MaintainersThis module is maintained by the OCA.OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.Currentmaintainer:This module is part of theOCA/rest-frameworkproject on GitHub.You are welcome to contribute. To learn how please visithttps://odoo-community.org/page/Contribute.