Enable Dark Mode!
overview-of-api-versioning-in-controllers-in-odoo-19.jpg
By: Anupriya Ashok

Overview of API Versioning in Controllers in Odoo 19

Technical Odoo 19 Odoo Enterprises Odoo Community

API versioning has emerged as a crucial component of preserving strong integrations with contemporary ERP systems. I recently upgraded my Odoo 19 customer-facing API endpoints and discovered firsthand the importance of proper versioning procedures. This is followed by a detailed guide on how to put this into practice in a real-world situation.

What is API Versioning in Odoo 19?

API versioning enables different versions of an endpoint to exist at the same time. Example:

  • /api/v1/customers for existing clients and
  • /api/v2/customers for your newer version.

With this configuration, older applications can continue to function as is while more recent ones utilize better endpoints. It's a clever method of expanding your API without upsetting current users.

Why Does Versioning Matter?

Even small changes to an API can cause integration issues when your Odoo instance is linked to external systems or mobile apps. Versioning assists you in avoiding that by:

  • Keeping older integrations functional
  • Allowing a smooth transition to new APIs. It's better to transition smoothly to new APIs.
  • Minimizing Downtime during Upgrades
  • Letting you retire outdated versions gradually

Think of it as a safety net: protection for your developers and clients alike against sudden changes.

Setting Up API Versioning in Odoo 19

Let's walk through the steps on how to set this up.

Step 1: Create the Module Structure

First of all, set up a custom Odoo module with a structure like this:

my_api_module/
+-- __init__.py
+-- __manifest__.py
+-- controllers/
   +-- __init__.py
   +-- main.py

Step 2: Create Version-Specific Controllers

File: controllers/main.py

# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request, Response

# -------- API v1 --------
class CustomerAPIv1(http.Controller):
   @http.route('/api/v1/customers', auth='public', methods=['GET'], type='http', csrf=False)
   def get_customers(self, **kwargs):
       # Use sudo to bypass access restrictions if needed
       customers = request.env['res.partner'].sudo().search([('phone', '!=', False)])
       data = [{
           'id': c.id,
           'name': c.name,
           'phone':c.phone
       } for c in customers]
       return request.make_json_response({
           'status': 'success',
           'data': data
       })
# -------- API v2 --------
class CustomerAPIv2(http.Controller):
   @http.route('/api/v2/customers', auth='public', methods=['GET'], type='http', csrf=False)
   def get_customers(self, **kwargs):
       customers = request.env['res.partner'].sudo().search([('email', '!=', False)])
       data = [{
           'id': c.id,
           'name': c.name,
           'email':c.email,
       } for c in customers]
       return request.make_json_response({
           'status': 'success',
           'data': data
       })

Understanding the Code

@http.route Decorator

A number of crucial parameters are accepted by the @http.route decorator:

  • URL path: Version numbers (/api/v1/, /api/v2/) are directly embedded in the route.
  • For open endpoints, set auth to "public"; for authenticated access, set it to "user."
  • techniques: GET, POST, PUT, and DELETE are permitted HTTP methods.
  • type: for RESTful APIs, use 'http'
  • To permit external access, csrf: Disabled for API endpoints

JSON Response Handling

Request for JSON Response Handling. The default method for returning JSON responses is make_json_response(). This assistive feature:

  • Correctly handles serialization to JSON and automatically sets the proper Content-Type headers.
  • offers reliable error-handling
  • makes code maintenance easier.

Access Control with sudo()

The standard access restrictions are circumvented by the `.sudo()` method. This is helpful, for instance, when using `auth='public'` because public routes by default lack user context. Be careful not to reveal information you don't want to show and use this sparingly:

Testing the API Endpoints

Test both the create and delete endpoints using Postman or curl:

  • Version 1 : http://localhost:8069/api/v1/customers — returns basic customer info (like name and phone).
  • Version 2: http://localhost:8069/api/v2/customers — includes extended details (like email addresses)

If both works as expected, then your versioning setup is complete.

API Versioning Best Practices

These practices are suggested based on implementation experience:

  • Use clear URLs: Always include version numbers (/api/v1/, /api/v2/, etc.).
  • Keep old versions active: Never take away the endpoints until all clients have upgraded.
  • Document changes: Explain clearly what's new in each version.
  • Maintain consistency: Use a common JSON format across all endpoints.
  • Consistency: A common JSON format should be used for all endpoints.
  • Plan ahead: Use timelines to retire older versions.
  • Handle errors nicely: Always return meaningful error messages

Odoo 19's API versioning enables you to develop your integrations in a methodical way without interfering with the current systems. By offering version-specific controllers and adhering to accepted best practices, you can feel secure enough to keep improving your APIs without sacrificing backward compatibility.

To read more about Overview of the Authenticated Controller in Odoo 19, refer to our blog Overview of the Authenticated Controller in Odoo 19.

FAQ

1. How many versions of the API should I keep up to date at once?

A. It is usually best to have two or three versions. Beyond this, it becomes challenging to properly maintain and test.

2. Is it appropriate to utilize distinct controller classes for every version?

A. Indeed. Conditional logic could be used in a single controller, but distinct classes offer easier maintenance and better code organization.

3. When is it better to use public access versus authentication?

A. Only use auth='public' for non-sensitive data. Use auth='user' or API tokens to properly authenticate any private information, including sales data and customer information.

4. Can I add new endpoints to an existing version?

A. Generally speaking, adding new endpoints to an existing version is safe. The risk comes from the modification of existing endpoints, which is when you introduce a new version.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message