Skip to content
Home » My Blog Tutorial » Integration with Odoo: Using API KEY in Postman

Integration with Odoo: Using API KEY in Postman

Integration with Odoo API with Postman

This tutorial explains Integration with Odoo, specifically Using API KEY within Postman. Therefore, you will learn how to connect to your Odoo instance and interact with its data using secure API calls. Consequently, this method provides a robust way to integrate external applications with Odoo.

What is Odoo’s JSON-RPC API?

Odoo, as a comprehensive suite of business applications, provides a powerful way to interact with its data and functionality remotely: the JSON-RPC API. Moreover, this API allows external applications, scripts, and services to communicate with an Odoo instance. Therefore, they can perform operations like reading, creating, updating, and deleting data.

JSON-RPC, as a lightweight remote procedure call protocol, uses JSON (JavaScript Object Notation) to encode its messages. Consequently, it’s simple, human-readable, and easily parsed by machines. Furthermore, Odoo’s implementation of JSON-RPC makes it a versatile tool for integration.

Why Use Postman?

Postman, as a popular API client, simplifies the process of working with APIs. Thus, it provides a user-friendly interface for constructing requests, viewing responses, and managing authentication. Moreover, for Odoo’s JSON-RPC API, Postman is invaluable for:

  • Testing API Calls: Quickly test different API calls and parameters without writing code.
  • Debugging: Inspect request and response details to troubleshoot integration issues.
  • Documentation: Postman collections can serve as living documentation for your Odoo API interactions.
  • Collaboration: Share collections with team members to standardize API usage.

Setting Up Odoo for API Access

Before you can start using Postman, you first need to configure Odoo to allow API access. Specifically, this involves creating an API key.

Creating an API Key in Odoo 18.0

API keys, as a secure way to authenticate external applications, provide controlled access to your Odoo data. Thus, follow these steps to create one:

  1. Log in as Administrator: First, ensure you are logged into your Odoo instance with an administrator account.
  2. Navigate to Settings: Then, go to the “Settings” app.
  3. Find Users & Companies: Depending on your Odoo 18.0 configuration, you might find API key settings under “Users & Companies” or directly within the “Settings” app.
  4. Manage Users: Next, select the user account for which you want to create the API key. It’s generally recommended to create a dedicated user for API access, rather than using your personal administrator account.
  5. Account Security: Within the user’s settings, find the “Account Security” tab or a similar section related to API keys.
  6. New API Key: Click on “New API Key” or a similar button to generate a new key.
  7. Description: Provide a clear and descriptive name for your API key (e.g., “Postman Integration”). This is crucial because it’s the only way to identify the key later.
  8. Validity Period: Set a validity period for the key. For testing, you might choose “1 Day,” but for production use, choose an appropriate duration based on your security policies.
  9. Generate Key: Click “Generate Key” or a similar button.
  10. Copy and Store Securely: Odoo will display the generated API key. Immediately copy this key and store it in a secure location, such as a password manager. Odoo will not show you this key again. Image: mpv-shot0002.jpg shows the API key creation screen in Odoo.
    Image: mpv-shot0003.jpg shows the generated API key with the warning to store it securely.

Configuring Postman for Odoo JSON-RPC

Now that you have an API key, you can configure Postman to interact with your Odoo instance.

Creating a Postman Environment

Environments in Postman, as a way to store variables, make it easy to switch between different configurations (e.g., development, testing, production). Thus, create an environment for your Odoo connection:

  1. New Environment: In Postman, click on the “Environments” tab (usually on the left sidebar) and then click the “+” icon to create a new environment.
  2. Environment Name: Give your environment a descriptive name (e.g., “Odoo 18.0 Local”).
  3. Add Variables: Add the following variables, replacing the placeholder values with your actual Odoo instance details:
    | Variable          | Value                                  |
    | :---------------- | :------------------------------------- |
    | `url`             | `http://localhost:8018`                |
    | `db_name`         | Your Odoo database name (e.g., `tutorial`) |
    | `uid`             | The User ID (see below)                |
    | `token`           | Your generated API key                  |
    | `employee_model`  | `hr.employee`                          |

Finding the User ID (uid): The uid is an internal Odoo identifier for the user. You can find it by enabling developer mode (go to Settings -> General Settings -> Developer Tools -> Activate Developer Mode), then going to Settings -> Users & Companies -> Users, selecting the user you’re using for the API, and looking at the URL. The uid will be a number in the URL (e.g., ...#id=6&... means uid is 6). Alternatively, you can get the uid via an initial authentication request (covered in a later section).

Creating a Postman Collection

Collections, as a way to group related requests, help organize your API calls. Thus, create a collection for your Odoo interactions:

  1. New Collection: In Postman, click on the “Collections” tab and then click the “+” icon to create a new collection.
  2. Collection Name: Give your collection a descriptive name (e.g., “Odoo 18.0 API”).

Making Your First JSON-RPC Request: search_read

The search_read method, as one of the most commonly used methods in Odoo’s API, allows you to retrieve data from any model. Thus, let’s create a request to fetch data from the hr.employee model:

  1. New Request: Within your Odoo collection, click “Add Request”.
  1. Request Name: Give your request a name (e.g., “Get Employees”).
  2. Request Type: Set the request type to POST.
  3. Request URL: Enter {{url}}/jsonrpc. This uses the url variable from your environment.
  4. Headers: Add a header:
    • Content-Type: application/json
  5. Body:
    • Select raw and choose JSON as the body type.
    • Enter the following JSON payload:
```json
    {
      "jsonrpc": "2.0",
      "method": "call",
      "params": {
        "service": "object",
        "method": "execute_kw",
        "args": [
          "{{db_name}}",
          "{{uid}}",
          "{{token}}",
          "{{employee_model}}",
          "search_read",
          [[["id", "=", 10]]],
          {
            "fields": ["name", "department_id"]
          }
        ]
      }
    }
    ```
  • Explanation:
    * "jsonrpc": "2.0": Specifies the JSON-RPC version.
    * "method": "call": Indicates a standard method call.
    * "params": Contains the parameters for the call.
    * "service": "object": Specifies the Odoo service to use (almost always “object” for model interactions).
    * "method": "execute_kw": The core method for executing model operations.
    * "args": An array of arguments:
    * "{{db_name}}": Your database name (from the environment).
    * "{{uid}}": Your user ID (from the environment).
    * "{{token}}": Your API key (from the environment).
    * "{{employee_model}}": The Odoo model to interact with (hr.employee).
    * "search_read": The specific method to call on the model.
    * [[["id", "=", 10]]] : A domain that filters the results. This example retrieves the employee with an ID of 10.
    * {"fields": ["name", "department_id"]}: Specifies which fields to retrieve. This example retrieves the employee’s name and department.
  1. Select Environment: Make sure you have selected your Odoo environment (e.g., “Odoo 18.0 Local”) in the top-right corner of Postman.
  2. Send Request: Click the “Send” button.

Image: mpv-shot0001.jpg shows the Postman request configuration with variables.

Image: mpv-shot0004.jpg shows the Postman request with the API key directly pasted in.

Image: mpv-shot0005.jpg shows the successful response from Odoo.

Interpreting the Response

If your request is successful, you should receive a 200 OK status code. Consequently, the response body will contain a JSON object with the results of your search_read operation:


```json
{
    "jsonrpc": "2.0",
    "id": null,
    "result": [
        {
            "id": 10,
            "name": "Keith Byrd",
            "department_id": [
                4,
                "Management / Research & Development"
            ]
        }
    ]
}
  • "result": This array contains the data retrieved from Odoo. In this case, it contains a single object representing the employee with ID 10.
  • "id", "name", "department_id": These are the fields you requested. Note that department_id is itself an array containing the ID and name of the department.

The transcript mentions two primary authentication methods for interacting with Odoo’s JSON-RPC API: API keys and session cookies. This blog post focuses on API keys, but it’s important to understand the difference.

  • Mechanism: API keys, as long, randomly generated strings, are passed directly in the request body (as shown in the search_read example).
  • Pros:
    • Stateless: Each request is self-contained and doesn’t rely on a previous login.
    • Secure: API keys can be easily revoked and have a defined validity period.
    • Best Practice: API keys are generally the recommended approach for external integrations.
  • Cons:
    • Requires careful management and secure storage.

Session Cookies (Less Common for Integrations)

  • Mechanism: Session cookies, as obtained through a separate /web/session/authenticate call, are stored in the Postman cookie jar and automatically included in subsequent requests.
  • Pros:
    • Can be useful for mimicking a user’s browser session.
  • Cons:
    • Stateful: Requires an initial authentication request to establish the session.
    • Less Secure: Session cookies can be more vulnerable to certain types of attacks.
    • Not Ideal for Integrations: Session cookies are generally less suitable for automated integrations.

The transcript briefly touches on using session cookies, but for most integration scenarios, API keys are the preferred and more secure method.

Alternative Authentication Request (for uid retrieval)

If you don’t know your uid, you can obtain it through an initial authentication request. This is not necessary if you already know your uid and are using an API key. This section is included for completeness.

  1. New Request: Create a new request in Postman.
  2. Request Name: Name it (e.g., “Authenticate”).
  3. Request Type: POST
  4. Request URL: {{url}}/jsonrpc
  5. Headers:
    • Content-Type: application/json
  6. Body:{ "jsonrpc": "2.0", "method": "call", "params": { "service": "common", "method": "login", "args": [ "{{db_name}}", "{{user_login}}", "{{user_pass}}" ] }, "id": 1 }
    • Replaced user_login and user_pass with appropiate value.
  7. Send Request: Click “Send”.

The response will include the uid:

{
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "uid": 6,
        "is_system": true,
        "is_admin": true,
        "user_context": {
            "lang": "en_US",
            "tz": "Europe/Brussels",
            "uid": 6
        },
        "db": "tutorial",
        "server_version": "17.0+e",
        "server_version_info": [
            17,
            0,
            0,
            "final",
            0,
            ""
        ],
        "support_url": "https://www.odoo.com/buy",
        "name": "Mitchell Admin",
        "username": "admin",
        "partner_id": 4,
        "company_id": 1,
        "web.base.url": "http://localhost:8018",
        "active_ids_limit": 20000,
        "max_file_upload_size": 125829120,
        "profile_session": null,
        "profile_collectors": null,
        "profile_params": null,
        "show_effect": true,
        "display_switch_company_menu": true,
        "cache_hashes": {
            "translations": "497f6eca-6276-4993-897b-3365b5cedd1c"
        },
        "currencies": {
            "1": {
                "name": "EUR",
                "symbol": "€",
                "position": "after",
                "digits": [
                    69,
                    2
                ],
                "rounding": 0.01
            },
            "2": {
                "name": "USD",
                "symbol": "$",
                "position": "before",
                "digits": [
                    69,
                    2
                ],
                "rounding": 0.01
            }
        }
    }
}

You would then use this uid (in this example, 6) in your subsequent search_read requests. However, with an API key, you can skip this authentication step and use the uid you found in the Odoo user settings.

Other execute_kw Operations

search_read is just one of many operations you can perform with execute_kw. Here are a few others:

  • create: Creates a new record in the specified model.
  • write: Updates an existing record.
  • unlink: Deletes a record.
  • search: Searches for records matching a domain (returns only IDs).

The general structure of the request remains the same; you just change the "method" and the "args" accordingly.

Example: create

{
  "jsonrpc": "2.0",
  "method": "call",
  "params": {
    "service": "object",
    "method": "execute_kw",
    "args": [
      "{{db_name}}",
      "{{uid}}",
      "{{token}}",
      "hr.employee",
      "create",
      [{
        "name": "New Employee",
        "department_id": 4  // Replace with the actual department ID
      }]
    ]
  },
  "id": 2
}

This request creates a new employee with the name “New Employee” in department ID 4.

Example: write

{
  "jsonrpc": "2.0",
  "method": "call",
  "params": {
    "service": "object",
    "method": "execute_kw",
    "args": [
      "{{db_name}}",
      "{{uid}}",
      "{{token}}",
      "hr.employee",
      "write",
      [10, {  // Update employee with ID 10
        "name": "Updated Name"
      }]
    ]
  },
  "id": 3
}

This request updates the name of the employee with ID 10 to “Updated Name”.

{
  "jsonrpc": "2.0",
  "method": "call",
  "params": {
    "service": "object",
    "method": "execute_kw",
    "args": [
      "{{db_name}}",
      "{{uid}}",
      "{{token}}",
      "hr.employee",
      "unlink",
      [10] // Delete employee with ID 10
    ]
  },
  "id": 4
}

This request deletes the employee with ID 10.

Error Handling

If your request fails, Odoo will return a JSON-RPC error response. Thus, pay close attention to the status code (it won’t be 200 OK) and the "error" field in the response body. Consequently, common errors include:

  • Invalid API Key: Double-check your API key and ensure it hasn’t expired.
  • Incorrect Database Name: Verify your db_name variable.
  • Incorrect User ID: Make sure you’re using the correct uid.
  • Model or Method Does Not Exist: Check your model and method names for typos.
  • Access Rights Issues: The user associated with the API key might not have the necessary permissions to perform the requested operation.

Conclusion

This tutorial has provided a comprehensive guide to integrating with Odoo using API keys and Postman. Therefore, by following these steps, you can securely connect to your Odoo instance and perform various operations on its data. Furthermore, remember to store your API key securely and consult the official Odoo documentation (https://www.odoo.com/documentation/17.0/developer/howtos/web_services.html) for more advanced usage and details on specific API methods.


Discover more from teguhteja.id

Subscribe to get the latest posts sent to your email.

Leave a Reply

Optimized by Optimole
WP Twitter Auto Publish Powered By : XYZScripts.com

Discover more from teguhteja.id

Subscribe now to keep reading and get access to the full archive.

Continue reading