Enhancing Odoo Functionality: An Overview of Remote Procedure Calls (RPC)


When it comes to enterprise resource planning (ERP) software, Odoo is a strong and adaptable choice for companies of all sizes. Combining a wealth of capabilities with a flexible architecture, it helps businesses increase productivity, optimize processes, and obtain insightful data. Although Odoo has some amazing core features, this platform's true power is in its ability to be extended through custom programming. Using Remote Procedure Call (RPC) protocols is one of the main ways to extend and integrate Odoo with other systems.


This article aims to provide an overview of Odoo RPC. We will examine its various varieties, delve into its fundamental ideas, and show how it makes it possible for Odoo and outside apps to communicate seamlessly. By understanding Odoo RPC, developers can harness its potential to create robust, scalable, and efficient solutions that enhance the overall functionality of the Odoo ecosystem.

What is Odoo RPC?

With the use of the Remote Procedure Call (RPC) protocol, a software can carry out operations on a distant server just like it would with local calls. Developers can concentrate on the logic rather than the intricacies of the network since RPC encapsulates the communication process between the client and the server. RPC is used in the Odoo environment to communicate with the Odoo server from outside programs or scripts, enabling smooth automation and integration.


Facilitating communication between a client application and the Odoo server is the primary goal of Odoo RPC. Developers can use RPC to execute a number of tasks in the Odoo database, including changing data, deleting entries, adding records, and querying data. The ability to automate corporate operations, integrate Odoo with other systems, and expand its capabilities all depend on this connection.

Types of RPC in Odoo:

Odoo supports two primary types of RPC protocols: XML-RPC and JSON-RPC.


  1. XML-RPC:

A protocol called XML-RPC employs HTTP as a transport method and XML as an encoding for its calls. It allows clients to call methods on a remote server, passing parameters and receiving responses in XML format.

Usage: XML-RPC is widely used in Odoo due to its simplicity and ease of integration with various programming languages.


2. JSON-RPC:

    • JSON-RPC is a protocol similar to XML-RPC but uses JSON (JavaScript Object Notation) for encoding the calls and responses. JSON-RPC is lighter and faster compared to XML-RPC due to the more compact JSON format.

    Usage: JSON-RPC is often preferred for web applications and services that require efficient data interchange.

    Comparison

    • Usage:
      • XML-RPC: Easy to use with various programming languages; well-documented in Odoo.
      • JSON-RPC: Preferred for web-based applications; suitable for modern web technologies.


    • Performance:
      • XML-RPC: A little bit slower because XML is a verbose language.
      • JSON-RPC: Faster and more efficient due to the compactness of JSON.


    • Ease of Implementation:
      • XML-RPC: Straightforward with plenty of libraries available for different languages.
      • JSON-RPC: Also easy to implement, especially in web environments, with many libraries supporting it.


    In conclusion, there are two reliable methods for communicating with the Odoo server: XML-RPC and JSON-RPC. Each has advantages. The choice between them depends on the specific requirements of the application and the environment in which it is being developed.

    Setting Up Odoo RPC

    Pre-requisites

    Before you start setting up Odoo RPC, ensure you have the following prerequisites:


    1. Odoo Instance:
    • It is necessary to have an active Odoo server instance. You can set up Odoo on a local machine or use a cloud-based instance.


    2. Python:

      • Python should be installed on your machine. Python versions 3.6 and higher are compatible with Odoo.


      3. Necessary Libraries:

        • For XML-RPC: The xmlrpc library, which is often included with Python's standard library, is required.
        • For JSON-RPC: You’ll need the requests library or similar for making HTTP requests. Install it using:
        pip install requests

        Environment Setup

        Step 1: Install Required Libraries


        • XML-RPC: Since Python's standard library provides xmlrpc.client for Python 3, usually no further installation is needed. Use xmlrpclib for Python 2.


        JSON-RPC: Ensure you have the requests library installed for making HTTP requests. You can install it using pip:

        pip install requests

        Step 2: Configure Odoo Server for RPC


        1. Verify Odoo Configuration:
        • Ensure that your Odoo server is running and accessible. Although RPC capabilities is typically enabled by default, be sure that RPC communication is permitted by your server settings.


        2. Check RPC Endpoints:

          • By default, Odoo supports XML-RPC and JSON-RPC endpoints at:
            • XML-RPC: http://<your-odoo-domain>/xmlrpc/2/
            • JSON-RPC: http://<your-odoo-domain>/jsonrpc
          • Ensure these endpoints are accessible by testing them in your web browser or using a tool like curl.


          Step 3: Basic Configuration


          1. Set Up Connection Parameters:

            • Obtain your Odoo server URL, database name, and credentials (username and password). These are necessary in order to authenticate and communicate via RPC with the Odoo server.


            2. Create a Configuration File (Optional):

            To streamline connection settings, create a configuration file with the following content:

            [odoo]
            url = http://<your-odoo-domain>
            database = <your-database-name>
            username = <your-username>
            password = <your-password>

            3. Initialize Connection in Your Code:

            For XML-RPC, you might use the following Python code to initialize the connection:

            import xmlrpc.client

            url = 'http://<your-odoo-domain>'
            db = '<your-database-name>'
            username = '<your-username>'
            password = '<your-password>'

            common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
            uid = common.authenticate(db, username, password, {})
            models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url))

            For JSON-RPC, you might use the following Python code to initialize the connection:

            import requests

            url = 'http://<your-odoo-domain>/jsonrpc'
            db = '<your-database-name>'
            username = '<your-username>'
            password = '<your-password>'

            headers = {
                'Content-Type': 'application/json',
            }

            def call(method, params):
                payload = {
                    'jsonrpc': '2.0',
                    'method': method,
                    'params': params,
                    'id': 1,
                }
                response = requests.post(url, json=payload, headers=headers)
                return response.json()
            1. Test Your Connection:
            • Run a quick test to make sure your RPC configuration is operational. For example, retrieve the server version or check user authentication.


            Your Odoo RPC environment will be configured and prepared for additional development and integration if you follow these instructions.

            Working with XML-RPC

            XML-RPC (Extensible Markup Language Remote Procedure Call) is a protocol that allows remote procedure calls over a network. It use HTTP as the transport technology and encodes both its calls and answers in XML format. When interacting with the Odoo server, XML-RPC is used to send requests to its API, which enables external applications to carry out different actions on the Odoo database.


            When it comes to expanding Odoo's functionality, automating activities, and integrating Odoo with other systems, XML-RPC is especially helpful. It provides a straightforward way to communicate with the Odoo server, making it an essential tool for developers working with Odoo.

            Connecting to Odoo using XML-RPC

            To connect to an Odoo server using XML-RPC, you'll need to use the xmlrpc.client library in Python. Here is an example of code to create a connection:

            import xmlrpc.client

            # Define the URL and credentials
            url = 'http://<your-odoo-domain>'
            db = '<your-database-name>'
            username = '<your-username>'
            password = '<your-password>'

            # Create XML-RPC server proxies
            common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
            models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url))

            # Authenticate user
            uid = common.authenticate(db, username, password, {})
            if not uid:
                raise Exception('Failed to authenticate user.')

            print('Successfully connected to Odoo with UID:', uid)

            Explanation of the Code:

            • import xmlrpc.client: Imports the XML-RPC client library for Python.
            • URL and Credentials: Replace <your-odoo-domain>, <your-database-name>, <your-username>, and <your-password> with your Odoo instance details.
            • Create Server Proxies: common is used for general methods like authentication, while models is used for interacting with Odoo models.
            • Authenticate User: Calls common.authenticate() to log in and obtain a user ID (uid).

            Performing Basic Operations

            Once connected, you may work with Odoo models using standard CRUD (Create, Read, Update, Delete) actions. Examples of each operation are given below:


            1. Create a Record:

            model_name = 'res.partner'
            values = {
                'name': 'New Partner',
                'email': 'new.partner@example.com',
            }

            new_record_id = models.execute_kw(db, uid, password, model_name, 'create', [values])
            print('Created record with ID:', new_record_id)

            2. Read Records:

            model_name = 'res.partner'
            record_id = 1


            record = models.execute_kw(db, uid, password, model_name, 'read', [[record_id]])
            print('Record data:', record)

            3. Update a Record:

            model_name = 'res.partner'
            record_id = 1
            values = {
                'email': 'updated.email@example.com',
            }

            models.execute_kw(db, uid, password, model_name, 'write', [[record_id], values])
            print('Record updated successfully.')

            4. Delete a Record:

            model_name = 'res.partner'
            record_id = 1

            models.execute_kw(db, uid, password, model_name, 'unlink', [[record_id]])
            print('Record deleted successfully.')

            Explanation of the Code:

            • Create: Uses models.execute_kw() to call the create method on the res.partner model with specified values.
            • Read: Uses models.execute_kw() to call the read method and retrieve data for a specific record.
            • Update: Uses models.execute_kw() to call the write method and update fields in a record.
            • Delete: Uses models.execute_kw() to call the unlink method and delete a record.

            Error Handling

            Error handling with grace is essential while using XML-RPC. The following common problems and solutions are listed:


            • Authentication Errors: Ensure that credentials are correct and that the user has the necessary permissions. Check the Odoo logs for detailed error messages.
            • Network Issues: Verify that the Odoo server is running and accessible. Check your network connection and firewall settings.
            • Invalid Data: Ensure that the data being sent to Odoo is correctly formatted and valid. For example, check that required fields are included when creating records.


            Exceptions in Code: Use try-except blocks to catch exceptions and handle them appropriately:

                # Example operation
                new_record_id = models.execute_kw(db, uid, password, model_name, 'create', [values])
            except xmlrpc.client.Fault as e:
                print('XML-RPC Fault:', e)
            except Exception as e:
                print('An error occurred:', e)

            By following these practices, you can effectively use XML-RPC to interact with your Odoo server, perform operations, and handle common errors.

            Working with JSON-RPC

            A protocol called JSON-RPC (JavaScript Object Notation Remote Procedure Call) enables the use of JSON as the data format for remote procedure calls. It offers a simple and effective method of carrying out network operations by encoding requests and responses in JSON. Because JSON-RPC is used to communicate with the Odoo server over HTTP, it is perfect for use with contemporary web apps and services.


            JSON-RPC is known for its simplicity and speed compared to XML-RPC, largely due to the more compact and human-readable JSON format. This protocol is well-suited for applications where performance and minimal overhead are crucial.

            Connecting to Odoo using JSON-RPC

            To connect to an Odoo server using JSON-RPC, you’ll use the requests library in Python to handle HTTP requests. Here’s a sample code snippet to establish a connection:

            import requests
            import json

            # Define the URL and credentials
            url = 'http://<your-odoo-domain>/jsonrpc'
            db = '<your-database-name>'
            username = '<your-username>'
            password = '<your-password>'

            # Define headers
            headers = {
                'Content-Type': 'application/json',
            }

            # Function to call the JSON-RPC API
            def call(method, params):
                payload = {
                    'jsonrpc': '2.0',
                    'method': method,
                    'params': params,
                    'id': 1,
                }
                response = requests.post(url, json=payload, headers=headers)
                return response.json()

            # Authenticate user
            auth_response = call('call', {
                'model': 'res.users',
                'method': 'check_access_rights',
                'args': ['read'],
                'kwargs': {},
            })
            print('Authentication response:', auth_response)

            Explanation of the Code:

            • import requests: Imports the requests library to handle HTTP requests.
            • import json: Imports the JSON library for handling JSON data.
            • URL and Credentials: Replace <your-odoo-domain>, <your-database-name>, <your-username>, and <your-password> with your Odoo instance details.
            • Headers: Sets the Content-Type header to application/json for the JSON-RPC request.
            • call Function: Sends a JSON-RPC request to the Odoo server and returns the response.
            • Authenticate User: Makes an API call to check access rights, which demonstrates how to interact with the Odoo server using JSON-RPC.

            Performing Basic Operations

            Once connected, you can perform basic CRUD (Create, Read, Update, Delete) operations on Odoo models. Here are examples of each operation:


            1. Create a Record:

            model_name = 'res.partner'
            values = {
                'name': 'New Partner',
                'email': 'new.partner@example.com',
            }

            create_response = call('call', {
                'model': model_name,
                'method': 'create',
                'args': [values],
                'kwargs': {},
            })
            print('Created record ID:', create_response.get('result'))

            2. Read Records:

            model_name = 'res.partner'
            record_id = 1

            read_response = call('call', {
                'model': model_name,
                'method': 'read',
                'args': [[record_id]],
                'kwargs': {},
            })
            print('Record data:', read_response.get('result'))

            3. Update a Record:

            model_name = 'res.partner'
            record_id = 1
            values = {
                'email': 'updated.email@example.com',
            }

            update_response = call('call', {
                'model': model_name,
                'method': 'write',
                'args': [[record_id], values],
                'kwargs': {},
            })
            print('Update response:', update_response.get('result'))

            4. Delete a Record:

            model_name = 'res.partner'
            record_id = 1

            delete_response = call('call', {
                'model': model_name,
                'method': 'unlink',
                'args': [[record_id]],
                'kwargs': {},
            })
            print('Delete response:', delete_response.get('result'))

            Explanation of the Code:

            • Create: Sends a request to create a new record in the res.partner model with the specified values.
            • Read: Sends a request to read data from a record in the res.partner model.
            • Update: Sends a request to update fields in an existing record.
            • Delete: Sends a request to delete a record from the res.partner model.
            try:
                response = call('call', {
                    'model': 'res.partner',
                    'method': 'create',
                    'args': [values],
                    'kwargs': {},
                })
                print('Create response:', response.get('result'))
            except requests.exceptions.RequestException as e:
                print('Request error:', e)
            except Exception as e:
                print('An error occurred:', e)

            By following these practices, you can effectively use JSON-RPC to interact with your Odoo server, perform operations, and manage errors efficiently.

            Batch Operations

            Batch operations are a powerful feature in Odoo RPC that allows you to perform multiple operations in a single request. This can significantly reduce the number of network calls and improve performance.

            Example of Batch Operations with XML-RPC

            batch_requests = [
                {'model': 'res.partner', 'method': 'create', 'args': [{'name': 'Partner 1', 'email': 'partner1@example.com'}]},
                {'model': 'res.partner', 'method': 'create', 'args': [{'name': 'Partner 2', 'email': 'partner2@example.com'}]},
            ]

            results = [models.execute_kw(db, uid, password, request['model'], request['method'], request['args']) for request in batch_requests]
            print('Batch operation results:', results)

            Example of Batch Operations with JSON-RPC

            batch_requests = [
                {'model': 'res.partner', 'method': 'create', 'args': [{'name': 'Partner 1', 'email': 'partner1@example.com'}]},
                {'model': 'res.partner', 'method': 'create', 'args': [{'name': 'Partner 2', 'email': 'partner2@example.com'}]},
            ]

            def batch_call(requests):
                payload = [
                    {'jsonrpc': '2.0', 'method': req['method'], 'params': {'model': req['model'], 'args': req['args']}, 'id': idx}
                    for idx, req in enumerate(requests)
                ]
                response = requests.post(url, json=payload, headers=headers)
                return response.json()

            batch_response = batch_call(batch_requests)
            print('Batch operation results:', batch_response)

            Managing Transactions

            Managing transactions in Odoo RPC ensures data integrity and consistency. Transactions group multiple operations into a single unit of work, which either completes entirely or fails.

            Example with XML-RPC

            # Start a transaction
            models.execute_kw(db, uid, password, 'res.partner', 'create', [{'name': 'Transactional Partner'}])

            # Commit or rollback as needed

            Example with JSON-RPC

            # JSON-RPC doesn't natively support transactions, but you can manage transactions through Odoo's internal methods or handle errors manually.

            Note: Odoo’s internal transaction handling is done within the server-side code. Ensure that the operations you perform are atomic and handle errors appropriately to maintain consistency.

            Security Considerations

            1. Authentication Methods


            Ensure that you use secure authentication methods to protect your Odoo instance. Odoo supports several authentication mechanisms:


            • Basic Authentication: Send credentials with each request. Ensure that you use HTTPS to encrypt credentials in transit.
            • OAuth: Use OAuth tokens for more secure and flexible authentication.


            2. Ensuring Secure Communication


            • Use HTTPS: Always use HTTPS to encrypt the communication between your client and the Odoo server to protect sensitive data.
            • IP Whitelisting: Restrict access to your Odoo server by allowing only trusted IP addresses.
            • API Key Management: Manage API keys securely and rotate them periodically.

            Performance Tips

            1. Optimizing RPC Calls


            • Minimize Calls: Batch operations to reduce the number of RPC calls.
            • Use Filters and Limits: Use filters to retrieve only the necessary data and limit the number of records fetched.


            Example of Filtering Data

            # XML-RPC
            partners = models.execute_kw(db, uid, password, 'res.partner', 'search_read', [[['is_company', '=', True]], ['name', 'email']])

            # JSON-RPC
            partners = call('call', {
                'model': 'res.partner',
                'method': 'search_read',
                'args': [[['is_company', '=', True]], ['name', 'email']],
                'kwargs': {},
            })

            2. Best Practices for Efficient Interaction


            • Caching: Implement caching for frequently accessed data to reduce load on the Odoo server.
            • Asynchronous Processing: Use asynchronous processing for long-running operations to avoid blocking your application.
            • Error Logging: Implement robust error logging and monitoring to quickly identify and address performance issues.

            Debugging Techniques

            1. Logging


            Implement detailed logging to capture and analyze RPC interactions. This helps in troubleshooting issues and understanding the flow of data.


            2. Debugging Tools


            • Odoo Logs: Review Odoo server logs to identify issues related to RPC calls.
            • Network Analysis Tools: Use tools like Postman or Fiddler to inspect RPC requests and responses.


            3. Exception Handling


            Use try-except blocks to handle exceptions and provide meaningful error messages.


            Example with XML-RPC:

            try:
                result = models.execute_kw(db, uid, password, 'res.partner', 'read', [[1]])
            except xmlrpc.client.Fault as e:
                print('XML-RPC Fault:', e)
            except Exception as e:
                print('An error occurred:', e)

            Example with JSON-RPC:

            try:
                response = call('call', {
                    'model': 'res.partner',
                    'method': 'read',
                    'args': [[1]],
                    'kwargs': {},
                })
            except requests.exceptions.RequestException as e:
                print('Request error:', e)
            except Exception as e:
                print('An error occurred:', e)

            Through the application of these advanced usage techniques and best practices, you can guarantee dependable, safe, and effective RPC communication with your Odoo server.

            Odoo Fields Selection: Types, Customization, and Validation