How to Use JSON- RPC in Odoo 17: A Step-by-Step Guide

Picture of IndexWorld

IndexWorld

Odoo 17 is a robust ERP system that supports smooth integration with external applications through different APIs. One of the most effective methods of communicating with Odoo programmatically is through JSON-RPC (JavaScript Object Notation – Remote Procedure Call). JSON-RPC is a light, stateless protocol that supports structured requests and responses between a client and a server.

In this in-depth guide, we will take you deep into the realm of RPC Odoo 17. We will describe what JSON-RPC is, why it is useful, and how to utilize JSON RPC in Odoo 17 in your Odoo projects. Additionally, we will walk through real-life implementation using correct Odoo 17 coding practices and provide a detailed example for better understanding.

Understanding JSON-RPC

JSON-RPC is an RPC protocol encoded in JSON. It allows clients to run commands on a remote server without the need for complicated setup or communication layers. As opposed to REST APIs, which depend on pre-established HTTP verbs (GET, POST, PUT, DELETE), JSON-RPC employs a straightforward request-response model where all interactions are contained within JSON objects.

Example JSON-RPC Request

				
					{
  "jsonrpc": "2.0",
  "method": "call",
  "id": 1,
  "params": {
    "model": "product.template",
    "method": "search_read",
    "args": [[]],
    "kwargs": {"fields": ["id", "name", "list_price"], "limit": 4}
  }
}
				
			

Example JSON-RPC Response

				
					{
  "jsonrpc": "2.0",
  "id": 1,
  "result": [
    {"id": 101, "name": "Wireless Mouse", "list_price": 29.99},
    {"id": 102, "name": "Mechanical Keyboard", "list_price": 89.99}
  ]
}
				
			

Why JSON-RPC?

JSON-RPC provides a number of benefits when implementing Odoo with external systems:

  1. Lightweight and Efficient: JSON-RPC is lightweight compared to XML-RPC.
  2. Uniform Structure: The format of JSON helps in easier debugging and reading.
  3. Batch Processing Supported: You can send many requests in a single call.
  4. Stateless Protocol: No session tracking is required, reducing complexity.
  5. Language Agnostic: Works with Python, JavaScript, PHP, and many other languages.
  6. Quicker Execution: As opposed to multiple requests of REST APIs, JSON-RPC achieves quicker execution with structured bulk requests.
Why JSON-RPC?

Activating JSON-RPC in Odoo 17

You have to enable your Odoo instance’s support for remote API access first in order to be able to utilize JSON-RPC in Odoo 17. Enabling web service settings within the configuration file (odoo.conf) is needed to accomplish this.

Step 1: Enable JSON-RPC in Odoo Configuration

Modify the odoo.conf file and add the following lines:

				
					[options]
jsonrpc = True
jsonrpc_interface = 127.0.0.1
jsonrpc_port = 8069
				
			

Restart the Odoo server after making these changes.

Step 2: Implementing JSON-RPC in Odoo 17

Creating a JSON-RPC Endpoint in Odoo

We need to create a custom endpoint in Odoo that can be accessed via JSON-RPC. Here’s how you can create a controller to fetch sold products:

Python Controller Code

				
					rom odoo import http
from odoo.http import request

class ProductSnippetController(http.Controller):
    @http.route('/fetch_sold_products', auth='public', type='json')
    def retrieve_sold_items(self):
        items = request.env['product.template'].sudo().search_read([], ['name', 'list_price', 'id'], limit=4)
        return items
				
			

This controller defines an endpoint (/fetch_sold_products) that returns a JSON response containing sold product details.

Fetching Data via JSON-RPC in JavaScript

To fetch data using JSON-RPC in JavaScript, use the following Odoo module:

JavaScript Code

				
					/* @odoo-module /
import publicWidget from '@web/legacy/js/public/public_widget';
import { jsonrpc } from "@web/core/network/rpc_service";
import { renderToElement } from "@web/core/utils/render";

let CustomSnippetWidget = publicWidget.Widget.extend({
    selector: '.js_custom_snippet',
    start: function(){
        jsonrpc('/fetch_sold_products', {}).then((data)=>{
            if (data){
                this.$el.find("#sold_products").html(renderToElement('snippet.custom_snippet_template', {data: data}))
            }
        })
    }
});

publicWidget.registry.CustomSnippetWidget = CustomSnippetWidget;
				
			

Rendering template code:

				
					<?xml version="1.0" encoding="UTF-8" ?>
<templates>
    <t t-name="snippet.custom_snippet_template">
        <div class="w3-blue w3-hover-shadow w3-right">
            <div>
                <section>
                    <div class="list-group" id="items-list" role="tablist">
                        <div class="w3-card-44 w3-dark-blue">
                            <t t-foreach="data" t-as="item" t-key="item.id">
                                <a class="list-group-item list-group-item-action active" id="list-item" data-bs-toggle="list" href="#list-details" role="tab" aria-controls="list-details">
                                    <t t-out="item.name"/>: <t t-out="item.list_price"/>
                                </a>
                            </t>
                        </div>
                    </div>
                </section>
            </div>
        </div>
    </t>
</templates>
				
			

Real-Life Example

Suppose you operate an e-commerce site where you sell home appliances in your online store, and you want your website to dynamically display the 4 best-selling products. That is, instead of having to constantly update the product list manually, you can use JSON-RPC from the Odoo API. Now, every time a customer visits your site, the latest top-selling products are fetched automatically via JSON-RPC and displayed in real-time, improving accuracy and user experience.

Conclusion

JSON-RPC is a powerful and efficient protocol for interacting with the rpc Odoo 17. It provides a structured, lightweight, and scalable approach to performing CRUD operations, and automating processes. Using the proper implementation procedures, organizations can improve their integration capabilities and make data exchange between Odoo & third-party applications more seamless and efficient.

Additionally, through proper utilization of JSON-RPC, robust high-performing Odoo systems can be built integrating with third applications seamlessly.

Need Help? Get in touch

Drag or browse files

(For example a specification or a brief)

Frequently Asked Questions (FAQs)

What is JSON-RPC in Odoo 17?

Odoo 17 supports JSON-RPC, a remote procedure call protocol that provides JS (JavaScript) endpoints to allow external applications to use structured JSON requests and responses to communicate with Odoo.

How to use JSON-RPC in Odoo 17?

You can get started with JSON-RPC in Odoo 17 by enabling it in the odoo.conf configuration file, and then implementing various API endpoints by creating Odoo controllers that each respond to the JSON-RPC requests.

What are the benefits of using JSON-RPC in Odoo?

Communication with Odoo using JSON-RPC is faster and more performant, enabling batch requests and allowing the protocol to avoid the overhead involved with either REST or XML-RPC.

Is JSON-RPC better than REST API in Odoo?

Although JSON-RPC may provide a more performant and structured request format for multiple records or process batch jobs, REST API, because of more widespread usage, provides a richer set of endpoints and supports a more extensive set of HTTP request methods.

How do I debug JSON-RPC calls in Odoo?

If you want to debug API calls made to Odoo JSON-RPC, you can use standard logging mechanisms in Python, browser developer tools when issuing requests from JavaScript, or tools like Postman to test JSON-RPC API requests.
Close

put your text here

Contact Us