In the ever-evolving landscape of Enterprise Resource Planning (ERP) systems, seamless integration is no longer a luxury—it’s a necessity. As businesses strive for greater efficiency and connectivity, the ability to connect various systems and automate workflows becomes paramount. This is where the Odoo 19 API steps in, offering a robust and significantly improved interface for developers and system integrators.
For years, those working with Odoo integrations often faced the complexities and limitations of XML-RPC. While functional, it sometimes presented hurdles that slowed down development and increased integration complexity. With Odoo 19, a new era has dawned. The latest version introduces a modern, token-based API that not only simplifies the integration process but also enhances security and performance. This revolutionary change is a game-changer, providing an invaluable leap forward for anyone looking to build robust third-party integrations with Odoo.
Imagine a world where your external applications can effortlessly communicate with your Odoo instance, automating tasks, synchronizing data, and extending Odoo’s core functionalities with unprecedented ease. The Odoo 19 API makes this vision a reality. Its intuitive design and clear documentation empower developers to unlock Odoo’s full potential, ensuring your business operations are more connected, agile, and efficient than ever before. This article will guide you through the process, demonstrating how to leverage this powerful new API with practical, step-by-step Python examples. Get ready to transform your Odoo integration strategy!
Why the New Odoo 19 API is a Game-Changer
The shift to a token-based authentication system in the Odoo 19 API marks a significant departure from previous methods, bringing it in line with modern web service best practices. This change offers several compelling advantages:
- Enhanced Security: Tokens provide a more secure way to authenticate API requests. Instead of sending user credentials with every request, a temporary, single-use, or time-limited token is used. This reduces the risk of credential compromise and offers better control over access permissions.
- Simplified Integration: Developers will find the new API much easier to work with. The clear, REST-like structure, combined with comprehensive documentation, streamlines the process of integrating external applications. This means faster development cycles and fewer headaches.
- Improved Performance: The optimized request handling and authentication mechanism contribute to better performance, especially in scenarios involving high volumes of API calls.
- Modern Development Practices: Adopting a token-based approach aligns Odoo with contemporary API design principles, making it more accessible and familiar to a broader range of developers who are accustomed to similar patterns in other modern platforms.
- Comprehensive Documentation: Odoo 19 comes with vastly improved API documentation, providing clear examples for various operations like searching, reading, creating, updating, and deleting records. This wealth of information is a treasure trove for integrators.
This innovative API empowers you to build sophisticated integrations, extending Odoo’s capabilities to meet your unique business requirements. Whether you’re connecting Odoo with an e-commerce platform, a custom CRM, or an analytics dashboard, the new Odoo 19 API provides the foundation for seamless data exchange.
Step-by-Step Tutorial: Mastering the Odoo 19 API for Seamless Integrations
This tutorial will walk you through the essential steps to interact with your Odoo 19 instance using its new token-based API. We’ll use Python for our examples, as it’s a popular choice for backend integrations due to its readability and robust libraries.
Prerequisites:
Before you begin, ensure you have the following:
- An active Odoo 19 instance (e.g., running locally or hosted).
- Python 3 installed on your system.
- The
requestslibrary for Python. If you don’t have it, install it via pip:bash pip install requests - Basic understanding of Python and JSON.
1. Generating Your Odoo 19 API Key
The first and most critical step is to obtain an API key from your Odoo 19 instance. This key acts as your secure token for authentication.
- Log in to Odoo 19: Access your Odoo 19 instance using an administrator account or a user with permissions to manage API keys.
- Navigate to User Preferences: Click on your user icon (top right corner) and select “Preferences” or “My Profile.”
- Access Security Settings: Within your preferences, look for a “Security” tab or section.
- Create a New API Key:
- Click on the “New API Key” button or similar option.
- You will be prompted to enter your Odoo password for validation. This ensures only authorized users can generate keys.
- Provide a meaningful description for your API key (e.g., “Integration with [YourAppName]”).
- Set an expiration date: For enhanced security, it’s highly recommended to set an expiration date for your API key. This limits its validity and necessitates periodic regeneration, reducing long-term exposure risks.
- Click “Generate.”
- Securely Store Your API Key: Once generated, Odoo will display the API key. Crucially, copy this key immediately and store it in a secure location. This key will only be shown once. If you lose it, you’ll have to revoke it and generate a new one.
2. Setting Up Your Python Environment and Initializing Variables
Create a new Python file (e.g., odoo_api_client.py) and set up your environment with the necessary imports and variables.
import requests
import json
# --- Configuration ---
# Replace with the API key you generated in Odoo 19
API_KEY = "YOUR_API_KEY_HERE"
# Replace with the base URL of your Odoo 19 instance (e.g., "http://localhost:8069")
ODOO_BASE_URL = "YOUR_ODOO_URL_HERE"
# Replace with the name of your Odoo database
ODOO_DB_NAME = "YOUR_DATABASE_NAME_HERE"
# Define standard headers for all API requests
HEADERS = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
print("Odoo 19 API client initialized.")
Important Considerations for the Odoo 19 API:
- Authentication: The
Authorization: Bearer {API_KEY}header is fundamental for every request to the Odoo 19 API. Without it, you’ll likely encounter authentication errors (typically a 401 Unauthorized status). - JSON Payloads: All data sent to the API should be in JSON format, specified by
"Content-Type": "application/json".
3. Performing Basic Operations with the Odoo 19 API
Now, let’s explore how to perform common CRUD (Create, Read, Update, Delete) operations using the Odoo 19 API. We’ll focus on the res.partner model (Contacts) for demonstration, but these principles apply across various Odoo models.
3.1. Reading Records: Search and Read
The search_read method is incredibly versatile. It allows you to search for records that match specific criteria (domain) and simultaneously retrieve a specified set of fields for those records. This is a significant improvement over just search, which only returns IDs.
Code Example (odoo_api_client.py):
# --- Search and Read Contacts ---
def search_and_read_contacts(domain=[], fields=["display_name", "name", "email"]):
print("\n--- Searching and Reading Contacts ---")
url = f"{ODOO_BASE_URL}/api/search_read"
data = {
"model": "res.partner",
"domain": domain,
"fields": fields,
}
response = requests.post(url, headers=HEADERS, data=json.dumps(data))
if response.status_code == 200:
contacts = response.json()
print(f"Found {len(contacts)} contact(s):")
for contact in contacts:
print(f"- ID: {contact.get('id')}, Display Name: {contact.get('display_name')}, Email: {contact.get('email', 'N/A')}")
return contacts
else:
print(f"Error searching contacts: {response.status_code} - {response.text}")
return None
# Example Usage:
print("\n--- Reading all contacts ---")
all_contacts = search_and_read_contacts()
print("\n--- Reading contacts with email ---")
contacts_with_email = search_and_read_contacts(domain=[["email", "!=", False]])
The domain parameter is powerful for filtering. An empty list [] fetches all records. You can define complex filters, for instance, [["email", "!=", False]] to get contacts with an email.
3.2. Creating New Records: The create Method
Adding new data to Odoo is straightforward with the create method. You provide the model name and a dictionary of values for the new record.
Code Example (odoo_api_client.py):
# --- Create a New Contact ---
def create_contact(name, email=None):
print("\n--- Creating a New Contact ---")
url = f"{ODOO_BASE_URL}/api/create"
values = {
"name": name,
}
if email:
values["email"] = email
data = {
"model": "res.partner",
"values": values,
}
response = requests.post(url, headers=HEADERS, data=json.dumps(data))
if response.status_code == 200:
new_contact_id = response.json()
print(f"Successfully created new contact with ID: {new_contact_id}")
return new_contact_id
else:
print(f"Error creating contact: {response.status_code} - {response.text}")
return None
# Example Usage:
new_contact_id = create_contact("API Test Contact", "api.test@example.com")
if new_contact_id:
# Verify creation
search_and_read_contacts(domain=[["id", "=", new_contact_id]])
This demonstrates how easy it is to inject data into your Odoo instance programmatically, a core feature of the Odoo 19 API.
3.3. Updating Existing Records: The write Method
To modify existing records, you’ll use the write method. This requires the ID(s) of the record(s) you wish to update and a dictionary of the fields you want to change.
Code Example (odoo_api_client.py):
# --- Update an Existing Contact ---
def update_contact(contact_id, new_values):
print(f"\n--- Updating Contact ID: {contact_id} ---")
url = f"{ODOO_BASE_URL}/api/write"
data = {
"model": "res.partner",
"ids": [contact_id],
"values": new_values,
}
response = requests.post(url, headers=HEADERS, data=json.dumps(data))
if response.status_code == 200 and response.json() is True:
print(f"Contact ID {contact_id} updated successfully.")
# Verify update
search_and_read_contacts(domain=[["id", "=", contact_id]])
return True
else:
print(f"Error updating contact ID {contact_id}: {response.status_code} - {response.text}")
return False
# Example Usage: (Assuming `new_contact_id` was created previously)
if new_contact_id:
update_contact(new_contact_id, {"email": "updated.api.test@example.com", "phone": "+123456789"})
The write method returns True upon successful execution, making it simple to confirm your updates.
3.4. Deleting Records: The unlink Method
The unlink method is used to delete records. Exercise extreme caution when using this method, as deletions are permanent. You pass a list of IDs to be removed.
Code Example (odoo_api_client.py):
# --- Delete a Contact ---
def delete_contact(contact_id):
print(f"\n--- Deleting Contact ID: {contact_id} ---")
url = f"{ODOO_BASE_URL}/api/unlink"
data = {
"model": "res.partner",
"ids": [contact_id],
}
response = requests.post(url, headers=HEADERS, data=json.dumps(data))
if response.status_code == 200 and response.json() is True:
print(f"Contact ID {contact_id} deleted successfully.")
# Verify deletion (should not find it)
print("Attempting to read deleted contact:")
search_and_read_contacts(domain=[["id", "=", contact_id]])
return True
else:
print(f"Error deleting contact ID {contact_id}: {response.status_code} - {response.text}")
return False
# Example Usage: (Assuming `new_contact_id` was created previously)
if new_contact_id:
delete_contact(new_contact_id)
Always double-check the contact_id before initiating unlink operations, especially in production environments.
3.5. Calling Arbitrary Methods: The call Method
Beyond the standard CRUD operations, the Odoo 19 API also provides a call method. This allows you to execute any method defined on an Odoo model, passing arguments as required. This is particularly useful for triggering custom actions or complex business logic.
Code Example (odoo_api_client.py):
# --- Call a Custom Method (e.g., Archiving an Event) ---
def call_model_method(model_name, method_name, args):
print(f"\n--- Calling method '{method_name}' on model '{model_name}' ---")
url = f"{ODOO_BASE_URL}/api/call"
data = {
"model": model_name,
"method": method_name,
"args": args,
}
response = requests.post(url, headers=HEADERS, data=json.dumps(data))
if response.status_code == 200:
result = response.json()
print(f"Method call successful. Result: {result}")
return result
else:
print(f"Error calling method: {response.status_code} - {response.text}")
return None
# Example Usage: Archiving an Event
# First, let's create a temporary event to archive
event_creation_url = f"{ODOO_BASE_URL}/api/create"
event_data = {
"model": "calendar.event",
"values": {
"name": "My API Test Event 2025",
"start_date": "2025-01-01",
"stop_date": "2025-01-01"
}
}
event_response = requests.post(event_creation_url, headers=HEADERS, data=json.dumps(event_data))
created_event_id = None
if event_response.status_code == 200:
created_event_id = event_response.json()
print(f"Created event with ID: {created_event_id}")
# Now, archive it
if created_event_id:
call_model_method("calendar.event", "action_archive", [[created_event_id]])
# After archiving, you might want to delete it to clean up
delete_contact(created_event_id) # Re-using delete_contact function for simplicity, but it's really an unlink operation.
else:
print(f"Error creating event for archiving example: {event_response.status_code} - {event_response.text}")
# You could also call 'action_unarchive' to restore it.
This call method provides immense flexibility, allowing you to trigger any business logic available through Odoo’s ORM layer directly via the API. This is a powerful aspect of the Odoo 19 API.
Best Practices for Working with the Odoo 19 API
To ensure your integrations are robust, secure, and maintainable, consider these best practices:
- Security First:
- Keep API keys secret: Never hardcode API keys directly into client-side applications or publicly accessible code repositories. Use environment variables or secure configuration management.
- Set expiration dates: For API keys, always set an expiration date. This minimizes the risk if a key is compromised.
- Least Privilege: Grant the API key only the minimum necessary permissions required for its intended operations within Odoo.
- Error Handling: Implement comprehensive error handling in your client applications. The Odoo API returns meaningful HTTP status codes and JSON error messages that should be logged and acted upon.
- Rate Limiting: Be mindful of API rate limits (if applicable to your Odoo deployment or hosting provider). Excessive requests can lead to temporary blocking. Design your integration to handle retries with exponential backoff.
- Batch Operations: Where possible, utilize Odoo’s capabilities for batch operations (e.g., passing a list of IDs to
writeorunlink). This reduces the number of API calls and improves efficiency. - Official Documentation: Always refer to the official Odoo 19 API documentation. It’s the most reliable source for up-to-date information on models, methods, and specific API endpoints. You can typically find it at
YOUR_ODOO_URL/api/doc. - Testing: Thoroughly test your API integrations in a development or staging environment before deploying to production.
- Internal Linking Strategy: Consider linking this guide to other related Odoo development topics or integration tutorials on your blog. For example, “Explore other Odoo customization tips in our Odoo Development Guide.”
Conclusion: Your Gateway to Next-Level Odoo Integrations
The introduction of the new token-based Odoo 19 API represents a monumental leap forward for Odoo’s extensibility and integration capabilities. It streamlines development, enhances security, and empowers businesses to build more agile and interconnected systems than ever before. Gone are the days of wrestling with the intricacies of XML-RPC; the future is here, and it’s built on a foundation of modern, secure, and developer-friendly principles.
By following the steps and examples outlined in this guide, you are now equipped to start building powerful integrations that automate workflows, synchronize critical data, and extend the functionalities of your Odoo 19 instance. The possibilities are truly limitless, enabling you to unlock new efficiencies and drive innovation within your organization. Embrace the power of the Odoo 19 API and revolutionize the way your business leverages its ERP system.
Ready to dive deeper into Odoo 19’s capabilities? Explore more advanced development topics and integration strategies on our blog!
External Resources:
- Python Requests Library Documentation: https://requests.readthedocs.io/en/latest/
- Odoo Official Documentation (General): https://www.odoo.com/documentation/
Discover more from teguhteja.id
Subscribe to get the latest posts sent to your email.

