Blog Post

...

Implement REST-endpoint in Odoo and invoke it

REST is an architectural style to build HTTP based webservices. We can claim it is a de-facto standard to create interoperable APIs for multiple app integrations. And it’s pretty often required to integrate Odoo with other 3d-party software. In this article we will figure out how to do it.

Assume that we need to create an Odoo endpoint that will return a contact (res.partner) by phone number. And then invoke this endpoint by a 3d-party app, i.e. Postman in our case. Here’s how this endpoint will look in Odoo:

@http.route('/rest_api/public/partner/<string:phone>', auth='user', type='http', csrf=False)
def get_partner(self, phone, **kw):
	res = dict()
	partner = request.env['res.partner'].search(['|', ('phone', '=like', '%' + phone), ('mobile', '=like', '%' + phone)], limit=1)
	if partner:
		res['name'] = partner.name
		res['id'] = partner.id
		res['commercial_company_name'] = partner.commercial_company_name
		res['email'] = partner.email
		res['phone'] = partner.phone
		res['mobile'] = partner.mobile
	else:
		res['search_by_phone'] = phone
		res['name'] = res['commercial_company_name'] \
			= res['email'] = res['phone'] = res['mobile'] = False
		res['id'] = -1
	wrapper = []
	wrapper.append(res)
	return json.dumps(wrapper)

What can we say about this endpoint:

  1. Phone number comes as a REST-styled URL parameter, i.e. /<phone>
  2. CSRF protection is turned off because this is how it should be for any REST-API in Odoo (see a comment in core py of Odoo)
  3. In current case the request of type ‘http’ is used (body type == x-www-form-encoded). We could use json request as well, but in that case a request body should be specified as “{}” for empty body, plus header content-type set to ‘application/json’
  4. This endpoint can be invoked by either GET or POST method, none of the code should be changed.

To call our custom API we also need to provide an authentication for it. First of all we should do an auth within Odoo, this can be done by invocation of Odoo core method /web/session/authenticate. This is how it looks in Postman:

image

As a result this method returns a cookie (with a session token) that is stored in Postman for future use. After that we can call our custom endpoint, the auth cookie is already there within a request:

image

Body should be empty for current request and of type form-urlencoded (http-type request). The result looks so:

image

This is how we got the result from Odoo by means of 3d-party software Postman.

In this article we’ve found out how to create RESTful API in Odoo to make it possible to communicate to it from the outside. If you have any questions feel free to write a comment.

Comments (0)

Tags: odoo


0 comments

Leave a Comment