Enable Dark Mode!
how-to-connect-to-an-odoo-16-using-restful-api.jpg
By: Yassir Irfan

How to Connect to an Odoo 16 Using RESTful API

Odoo Enterprises Odoo Community

In today's interconnected world, integrating and communicating with various software systems is crucial for businesses.
Odoo, a powerful open-source ERP platform, offers a RESTful API that enables seamless interaction with external applications. This comprehensive guide will walk you through the process of connecting to an Odoo instance using the RESTful API. 
By following the steps outlined below, you'll be able to establish a connection, authenticate your credentials, and make API requests to access and manipulate data within your Odoo system.

Step 1: Import Required Modules:

Begin by importing the necessary Python modules: `requests` for handling HTTP requests and `json` for working with JSON data. These modules are essential for interacting with the Odoo RESTful API. Make sure you have these modules installed in your Python environment.
import requests
import json

Step 2: Define the Connection Function (auth='user'):

Create a Python function called `connect_to_odoo_api` that will serve as the core component for connecting to your Odoo instance. This function handles authentication, header configuration, and API requests.
def connect_to_odoo_api(path, parameters):
    """
    Connects to an Odoo instance using the RESTful API.
    Args:
        path (str): The API endpoint path.
        parameters (dict): The request parameters.
    Returns:
        dict or None: The JSON response from the API, or None if an error occurs.
    """
    # Function code goes here

Step 3: Set Endpoint URL and Authentication Credentials (auth='user'):

In the `connect_to_odoo_api` function, set the endpoint URL for your Odoo instance and provide the necessary authentication credentials.
url = 'http://example.com:8069/'
db = 'sample_db'
username = 'sample_user'
password = 'sample_password'
Replace the placeholder values with the actual URL of your Odoo instance, the name of your database, and your Odoo username and password.

Step 4: Authenticate and Obtain a Session ID (auth='user'):

To establish a session with your Odoo instance, send an authentication request to validate your credentials and obtain a session ID.
session_url = f'{url}/web/session/authenticate'
data = {
    'jsonrpc': '2.0',
    'method': 'call',
    'params': {
        'db': db,
        'login': username,
        'password': password,
    }
}
session_response = requests.post(session_url, json=data)
session_data = session_response.json()
The authentication request is made to the `/web/session/authenticate` endpoint, passing the required authentication parameters. The response contains the session ID, which will be used for subsequent API requests.

Step 5: Handle Authentication Response (auth='user'):

Check the authentication response to verify the success of the authentication process and retrieve the session ID. If authentication fails, display an error message.
if session_data.get('result') and session_response.cookies.get('session_id'):
    session_id = session_response.cookies['session_id']
else:
    print(f'Error: Failed to authenticate - {session_data.get("error")}')
    return None
If authentication is successful, extract the session ID from the response cookies. If authentication fails, display an error message and return `None`.

Step 6: Set Request Headers (auth='user'):

Before making API requests, set the required headers, including the session ID obtained in the previous step. These headers ensure proper authorization for API calls.
headers = {
    'Content-Type': 'application/json',
    'Cookie': f"session_id={session_id}",
}
The `Content-Type` header indicates that the request payload is in JSON format, while the `Cookie` header includes the session ID. These headers will be included in subsequent API requests.
There are two cases for connecting Odoo using the RESTful API: one with authentication (auth='user') and the other without authentication (auth='public').

Case 1: With Authentication (auth='user')

In this case, we assume that authentication is required to access the API endpoints in Odoo. Here's how you can connect to Odoo with authentication:

Step 7.1 (With Authentication): Send API Request:

def connect_to_odoo_api_with_auth(path, parameters, username, password):
    """
    Connects to an Odoo instance using the RESTful API with authentication.
    Args:
        path (str): The API endpoint path.
        parameters (dict): The request parameters.
        username (str): Odoo username.
        password (str): Odoo password.
    Returns:
        dict or None: The JSON response from the API, or None if an error occurs.
    """
    url = 'http://example.com:8069/'  # Update with your Odoo instance URL
    endpoint = f'{url}{path}'
    payload = {
        'params': parameters,
    }
    try:
        response = requests.post(endpoint, headers={'Content-Type': 'application/json'}, auth=(username, password), json=payload)
        try:
            return response.json()
        except Exception as e:
            return e
    except KeyError:
        print("The 'result' key is missing in the JSON response.")
        return None
With this setup, you can use the `connect_to_odoo_api_with_auth` function to connect to Odoo and make authenticated requests.

Step 8.1 (With Authentication): Implement API Controller in Odoo:

from odoo import http
import json
class OdooAPIController(http.Controller):
    @http.route('/api/endpoint', type='json', auth='user')
    def api_endpoint(self, **kw):
        # Access the request parameters
        parameters = json.loads(http.request.httprequest.data)
        # Process the API request and return the response
        response = {
            'status': 'success',
            'message': 'API request received with authentication',
            'data': {
                'parameters': parameters
            }
        }
        return response
In this case, authentication is required (`auth='user'`) to access the `/api/endpoint` route.

Case 2: Without Authentication (auth='public')

In this case, we assume that no authentication is required to access the API endpoints in Odoo. Here's how you can connect to Odoo without authentication:

Step 7.2 (Without Authentication): Send API Request:

def connect_to_odoo_api_without_auth(path, parameters):
    """
    Connects to an Odoo instance using the RESTful API without authentication.
    Args:
        path (str): The API endpoint path.
        parameters (dict): The request parameters.
    Returns:
        dict or None: The JSON response from the API, or None if an error occurs.
    """
    url = 'http://example.com:8069/'  # Update with your Odoo instance URL
    endpoint = f'{url}{path}'
    payload = {
        'params': parameters,
    }
    try:
        response = requests.post(endpoint, headers={'Content-Type': 'application/json'}, json=payload)
        try:
            return response.json()
        except Exception as e:
            return e
    except KeyError:
        print("The 'result' key is missing in the JSON response.")
        return None
With this setup, you can use the `connect_to_odoo_api_without_auth` function to connect to Odoo and make requests without the need for authentication.

Step 8.2 (Without Authentication): Implement API Controller in Odoo:

from odoo import http
import json
class OdooAPIController(http.Controller):
    @http.route('/api/endpoint', type='json', auth='public')
    def api_endpoint(self, **kw):
        # Access the request parameters
        parameters = json.loads(http.request.httprequest.data)
        # Process the API request and return the response
        response = {
            'status': 'success',
            'message': 'API request received without authentication',
            'data': {
                'parameters': parameters
            }
        }
        return response
In this case, no authentication is required (`auth='public'`) to access the `/api/endpoint` route.
You can choose the appropriate approach (with or without authentication) based on your Odoo setup and security requirements.

Conclusion:

You now know how to connect to an Odoo instance using the RESTful API. By following the step-by-step instructions provided in this guide, you can successfully establish a connection, authenticate your credentials, and interact with your Odoo system through API calls. Additionally, you have learned how to implement a custom API controller in Odoo to accept and process API requests. Leverage the power of the Odoo RESTful API to streamline your business processes and enhance integration with external applications.
To read more about connecting Gmail to Odoo 16 using Google OAuth, refer to our blog How to Connect Gmail to Odoo 16 Using Google OAuth


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



0
Comments



Leave a comment



whatsapp
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