| Availability |
Odoo Online
Odoo.sh
On Premise
|
| Lines of code | 9859 |
| Technical Name |
muk_rest |
| License | See License tab |
| Website | http://www.mukit.at |
| Versions | 10.0 11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0 |
MuK REST for Odoo
A customizable RESTful API for Odoo
MuK IT GmbH - www.mukit.at
Overview
Enables a REST API for the Odoo server. The API provides routes to authenticate and retrieve a token. Afterwards, a comprehensive set of routes to interact with the server are provided. The API can be used by any language or framework that can make HTTP requests and receive JSON responses. It works with both the Community and the Enterprise Edition.
The module exposes endpoints for CRUD operations, file management,
report generation, security checks and system introspection. All
routes are served under a configurable base URL (default
/api/v2)
and return JSON responses.
To activate the routes even if no database is selected, the module should be loaded right at the server start. This can be done by editing the configuration file or passing a load parameter to the start script.
Parameter:
--load=web,muk_rest
To access the API in a multi-database environment without a db
filter, the name of the database must be provided with each request
via a query parameter or a custom header (e.g.
?db=database_name).
Key Features
Interactive Documentation
The interactive documentation page at
/api/docs
is powered by Swagger UI and based on the OpenAPI 3.0 specification.
All endpoints are described in detail and a number of defined schemas
make it easy to understand the required parameters and returned
results. Custom endpoints are automatically included.
The built-in Model Explorer lets you browse every installed model, inspect its fields and instantly fire test requests â all without leaving the browser.
Custom Endpoints
In addition to the built-in API endpoints, custom endpoints can easily be added without writing any code. New endpoints are created in the backend and are immediately available through the API.
Three evaluation modes are available: Domain evaluation to query data with standard Odoo domain syntax, Server Action to execute a linked server action, and Python Code to run arbitrary Python code via safe_eval. Each endpoint can be public or protected and is automatically added to the Swagger UI documentation.
Connect to the API
The API supports authentication via OAuth1, OAuth2, Basic authentication (username and password or API key) and Bearer tokens. The interactive documentation supports OAuth2 and Basic authentication. The API has OAuth2 support for all 4 grant types. For OAuth clients, advanced security can be enabled to restrict which endpoints and parameters are allowed.
Quick Start - curl Examples
The fastest way to get started is with Basic authentication. The
examples below use
admin:admin
credentials (Base64-encoded as
YWRtaW46YWRtaW4=).
Replace the host, credentials and database name with your own values.
In a multi-database environment, add the
DATABASE
header to select the database.
# Check API version
curl https://your-odoo.com/api/v2
# Read partners (with fields and limit)
curl -X GET \
'https://your-odoo.com/api/v2/search_read/res.partner?fields=["name","email"]&limit=5' \
-H 'Authorization: Basic YWRtaW46YWRtaW4=' \
-H 'DATABASE: your-database'
# Create a partner
curl -X POST \
'https://your-odoo.com/api/v2/create/res.partner' \
-H 'Authorization: Basic YWRtaW46YWRtaW4=' \
-H 'DATABASE: your-database' \
-H 'Content-Type: application/json' \
-d '{"values": {"name": "Jane Doe", "email": "jane@example.com"}}'
# Update a partner
curl -X PUT \
'https://your-odoo.com/api/v2/write/res.partner' \
-H 'Authorization: Basic YWRtaW46YWRtaW4=' \
-H 'DATABASE: your-database' \
-H 'Content-Type: application/json' \
-d '{"ids": [42], "values": {"phone": "+1 555-0123"}}'
# Delete a partner
curl -X DELETE \
'https://your-odoo.com/api/v2/unlink/res.partner' \
-H 'Authorization: Basic YWRtaW46YWRtaW4=' \
-H 'DATABASE: your-database' \
-H 'Content-Type: application/json' \
-d '{"ids": [42]}'
# Duplicate a record
curl -X POST \
'https://your-odoo.com/api/v2/call/res.partner/copy' \
-H 'Authorization: Basic YWRtaW46YWRtaW4=' \
-H 'DATABASE: your-database' \
-H 'Content-Type: application/json' \
-d '{"ids": [1]}'
Clients
There are already very good REST clients in almost every programming language. For example, in Python there is the Requests library to make HTTP calls and Requests-OAuthlib to authenticate with OAuth, to name just one.
But in case you want to create your own client, you can automatically generate one based on the API documentation. The client is created by Swagger Codegen and can serve as a good starting point.
The API as a Framework
The REST API is also designed as a framework and can be used as a
basis for an extension to fit individual requirements. This code
example shows how easy it is to define an endpoint. The parameters
in the
docs
keyword argument are optional. If no parameters are given, dynamic
default values are generated based on the function signature.
from odoo import http
from odoo.http import request
from odoo.tools.misc import file_path
from odoo.addons.muk_rest.tools.http import make_json_response
from odoo.addons.muk_rest.tools.common import build_route
from odoo.addons.muk_rest import core
class CommonController(http.Controller):
@core.http.rest_route(
routes=build_route('/user'),
methods=['GET'],
protected=True,
docs=dict(
tags=['Common'],
summary='User',
description='Returns the current user.',
responses={
'200': {
'description': 'Current User',
'content': {
'application/json': {
'schema': {
'$ref': '#/components/schemas/CurrentUser'
},
'example': {
'name': 'Admin',
'uid': 2,
}
}
}
}
},
default_responses=['400', '401', '500'],
),
)
def user(self, **kw):
return make_json_response({
'uid': request.session and request.session.uid,
'name': request.env.user and request.env.user.name
})
Help and Support
Feel free to contact us, if you need any help with your Odoo
integration or additional features.
You will get 30 days of
support in case of any issues (except data recovery, migration or
training).
Our Services
Odoo
Development
Odoo
Integration
Odoo
Infrastructure
Odoo
Training
Odoo
Support
MuK REST API for Odoo
Enables a REST API for the Odoo server. The API has routes to authenticate and retrieve a token. Afterwards, a set of routes to interact with the server are provided. The API can be used by any language or framework which can make HTTP requests and receive responses with JSON payloads and works with both the Community and the Enterprise Edition.
The module exposes a comprehensive set of endpoints for CRUD operations, file management, report generation, security checks and system introspection. All routes are served under a configurable base URL (default /api/v2) and return JSON responses. In addition, the module ships with an interactive documentation page powered by Swagger UI and a Model Explorer for browsing fields and methods of every installed Odoo model.
The API allows authentication via OAuth1 and OAuth2 as well as with username and password, although an access key can also be used instead of the password. The interactive documentation supports OAuth2 and Basic authentication. The API has OAuth2 support for all 4 grant types. More information about the OAuth authentication can be found under the following links:
- OAuth1 - RFC5849
- OAuth2 - RFC6749
Requirements
Below you will find a list of requirements. These are not always mandatory to install the module, but without them the functionality will be limited.
OAuthLib
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic for Python. Without OAuthLib installed the OAuth1 and OAuth2 authentication methods are automatically disabled and only Basic authentication is available. To install OAuthLib please follow the instructions or install the library via pip.
pip install oauthlib
Installation
To install this module, you need to:
Download the module and add it to your Odoo addons folder. Afterward, log on to your Odoo server and go to the Apps menu. Trigger the debug mode and update the list by clicking on the "Update Apps List" link. Now install the module by clicking on the install button.
Upgrade
To upgrade this module, you need to:
Download the module and add it to your Odoo addons folder. Restart the server and log on to your Odoo server. Select the Apps menu and upgrade the module by clicking on the upgrade button.
Configuration
Server-wide Loading
In case the module should be active in every database just change the auto install flag to True. To activate the routes even if no database is selected the module should be loaded right at the server start. This can be done by editing the configuration file or passing a load parameter to the start script.
Parameter: --load=web,muk_rest
Multi-database Environment
To access the API in a multi-database environment without a db filter, the name of the database must be provided with each request via a query parameter or a custom header.
Query parameter: ?db=<database_name>
The header name and query parameter name are configurable via the rest_db_header and rest_db_param configuration parameters (defaults: DATABASE and db).
OAuth Configuration
To configure this module, you need to:
- Go to Settings -> API -> Overview. Here you can see an overview of all your API configurations (OAuth1 and OAuth2 clients).
- Click on Create or go to either Settings -> API -> Configuration -> OAuth1 or Settings -> API -> Configuration -> OAuth2 to create a new API configuration.
OAuth1 Configuration
Each OAuth1 configuration provides a Consumer Key and Consumer Secret (auto-generated, 20-50 characters). These credentials are used by the three-legged OAuth1 flow:
- Initiate -- POST /api/v2/authentication/oauth1/initiate to obtain a request token.
- Authorize -- Redirect the user to /api/v2/authentication/oauth1/authorize where they log in and grant access.
- Token -- POST /api/v2/authentication/oauth1/token to exchange the authorized request token for an access token.
OAuth2 Configuration
Each OAuth2 configuration provides a Client ID and Client Secret (auto-generated). Four grant types are supported:
- Authorization Code -- Requires at least one callback URL. The first callback in the list is the default.
- Implicit -- Token returned directly in the redirect URL fragment.
- Password Credentials -- Token obtained by sending username and password.
- Client Credentials -- Token obtained using client credentials alone. Requires a linked Odoo user to execute requests as.
OAuth2 endpoints:
- /api/v2/authentication/oauth2/authorize -- Authorization endpoint
- /api/v2/authentication/oauth2/token -- Token endpoint (issue / refresh)
- /api/v2/authentication/oauth2/revoke -- Token revocation endpoint
Access Rules
Each OAuth configuration can define Access Rules to restrict which API routes the client may call. Each rule specifies a route pattern (which may be a regular expression) and a set of parameter expressions. When the security mode is set to Advanced, only routes matching an applied rule are allowed.
Settings
Additional settings are available under Settings -> API -> Configuration -> Settings (General Settings page, API section):
Docs Security
Restrict access to the interactive API documentation (/api/docs) to members of a specific security group. When no group is selected, the documentation is accessible to any authenticated user.
OAuth1 Access Tokens
- Clean after (days) -- Expired OAuth1 access tokens are automatically cleaned up after this many days (default: 7).
OAuth2 Bearer Tokens
- Bearer token expiration (seconds) -- How long a bearer token is valid.
- Bearer token auto-vacuum (days) -- Expired tokens are automatically cleaned up after this many days.
Rate Limiting
- Max requests per window -- Maximum number of API requests per time window. Set to 0 to disable rate limiting.
- Window duration (seconds) -- The length of the rate limiting window.
When the limit is exceeded the API returns 429 Too Many Requests.
Configuration File Parameters
It is possible to further customize the API via a set of parameters inside the Odoo configuration file. The following parameters are available:
- rest_default_cors -- Sets the CORS attribute on all REST routes. Default: None
- rest_docs_security_group -- XML ID of an access group to protect the API docs. Default: None
- rest_docs_codegen_url -- URL of the Swagger Codegen service for client generation. Default: https://generator3.swagger.io/api
- rest_authentication_basic -- Enable Basic authentication on the REST API. Default: True
- rest_authentication_oauth1 -- Enable OAuth1 authentication on the REST API. Default: True
- rest_authentication_oauth2 -- Enable OAuth2 authentication on the REST API. Default: True
- rest_db_header -- Custom HTTP header name for the database name. Default: DATABASE
- rest_db_param -- Query parameter name for the database name. Default: db
- rest_logging -- Enable request/response logging. Default: True
- rest_logging_autovacuum -- Days after which log entries are automatically deleted. Default: 30
- rest_logging_attribute_limit -- Character limit for individual attribute values in logged request/response data. Default: 150
- rest_logging_content_limit -- Character limit for logged response content body. Default: 25000
- rest_debug -- Show full tracebacks in API error responses instead of generic messages. Default: False
Parameters from a configuration file can be loaded via the --config command.
Custom Endpoints
To extend the API and add your own routes, go to Settings -> API -> Configuration -> Endpoints and create a new endpoint. Each custom endpoint is served at /api/v2/custom/<endpoint_path>.
An endpoint can be public or protected (requires authentication). Three evaluation modes are available:
Domain
Evaluates a search domain on the configured model. The domain expression supports standard Odoo domain syntax. You can optionally restrict the returned fields by selecting specific fields in the Domain Fields tab. The query parameters limit, offset and order are supported. When the Wrap Response flag is enabled the result is wrapped in an envelope containing the endpoint name, model, domain, result list and count.
Server Action
Executes a linked server action (ir.actions.server). The request parameters are passed as active_id and active_ids in the action context. The return value of the action is sent back as the response.
Python Code
Executes arbitrary Python code via safe_eval. The following variables are available in the evaluation context:
- env -- the current Odoo environment
- model -- a recordset for the configured model
- params -- a dictionary of request parameters
- headers -- the HTTP request headers
- uid / user -- the current user ID / user record
- logger -- a Python logger instance
- time, datetime, dateutil, timezone -- date/time libraries
- json, b64encode, b64decode -- serialization utilities
- make_json_response, make_response -- response helpers
- responses, exceptions -- HTTP status helpers
The code can set one of the following variables to control the response:
- result -- a value that is JSON-serialized and returned
- content -- raw string content returned as-is
- response -- a full Werkzeug Response object
Endpoint Documentation
Each custom endpoint has a Docs tab where you can configure how it appears in the Swagger UI:
- Summary and Description -- displayed in the endpoint listing
- Parameters -- a JSON list of OpenAPI parameter objects
- Responses -- a JSON map of OpenAPI response objects
- Components -- additional OpenAPI schema components
- Default responses -- toggles for standard 200, 400, 401 and 500 responses
API Endpoints
All routes are prefixed with the configurable base URL (default /api/v2). Protected routes require authentication (Basic, OAuth1 or OAuth2) and are marked with a lock icon in the interactive documentation. Parameters can be passed as query parameters or in the JSON request body.
The API provides endpoints in the following categories:
- Server -- Public endpoints for version info, available languages, countries, current database and installed modules.
- Common -- Current user info, OpenID Connect user profile, company details and session information.
- Model (Search) -- Search, search-read, read-group aggregation and search-extract with relational field expansion.
- Model (Read) -- Display names, field reads, CSV/XLSX export and extract with nested relational data.
- Model (Create) -- Single/batch record creation and upsert (create-or-update by domain).
- Model (Write) -- Single and batch record updates.
- Model (Delete) -- Record deletion.
- Model (Call) -- Generic public method invocation on any model.
- File -- File and image download (by XML ID, attachment or field reference) and multipart file upload.
- Report -- List available reports and render them as PDF, HTML or text.
- Security -- Access rights, record rules, field access checks, group membership queries.
- System -- Model and field introspection, method signatures, record metadata and XML ID resolution.
For the complete endpoint reference with parameters and response schemas, visit the interactive Swagger UI documentation at /api/docs or go to Settings -> API -> Documentation -> Endpoints.
Authentication
The API supports three authentication methods. Protected routes (marked with a lock icon in Swagger UI) require one of these methods.
Basic Authentication
Send an Authorization header with the Basic scheme. The credentials are username:password (or username:api_key) encoded in Base64.
Example (admin:admin encoded in Base64):
Authorization: Basic YWRtaW46YWRtaW4=
Bearer Authentication
Send an Authorization header with the Bearer scheme using an Odoo API key.
Example:
Authorization: Bearer <api_key>
OAuth1 (RFC 5849)
Three-legged OAuth1 flow using consumer key/secret and request/access tokens. Requires the oauthlib Python library.
- POST /api/v2/authentication/oauth1/initiate -- Obtain a request token.
- Redirect user to /api/v2/authentication/oauth1/authorize to log in and grant access.
- POST /api/v2/authentication/oauth1/token -- Exchange the authorized request token for an access token.
OAuth2 (RFC 6749)
Standard OAuth2 flow with support for all four grant types. Requires the oauthlib Python library.
- Authorization endpoint: /api/v2/authentication/oauth2/authorize
- Token endpoint: /api/v2/authentication/oauth2/token
- Revocation endpoint: /api/v2/authentication/oauth2/revoke
The authentication method used (Basic, OAuth1, OAuth2) is tried in order. The first successful authentication wins. If all methods fail, the API returns 401 Unauthorized.
Interactive Documentation
The module includes an interactive API documentation page at /api/docs. It can also be reached via Settings -> API -> Documentation -> Endpoints.
The page has two tabs:
Swagger UI
The Swagger UI tab shows the full OpenAPI 3.0 specification for all built-in and custom endpoints. From here you can:
- Browse all endpoints grouped by category (Server, Common, Model, File, Report, Security, System, and any custom endpoint tags).
- See request parameters, request bodies and response schemas.
- Authorize using Basic authentication or OAuth2 via the lock icon on each protected endpoint or the global Authorize button.
- Try out any endpoint directly from the browser -- fill in parameters, click Execute and see the live response, curl command and request URL.
- Generate client SDKs in various languages (Python, Java, JavaScript, etc.) using the integrated Swagger Codegen service.
Model Explorer
The Model Explorer tab provides an interactive browser for all Odoo models the current user has read access to. For each model you can:
- See all fields with their type, description, module of origin, required/ readonly flags, relation targets and selection values.
- Browse all public methods with their full signature, parameter details, docstrings, introducing module and API decorators.
- Try methods directly from the UI -- select a method, fill in IDs, args and kwargs, and execute the call. The result or error is displayed inline along with the equivalent curl command.
- Filter and search models by name, and filter fields/methods within a model.
Request Logging
Every API request is logged automatically (unless disabled in the configuration file or per custom endpoint). Logs are accessible under Settings -> API -> Technical -> Logs (requires developer mode) and include:
- User, IP address, URL, HTTP method
- Full request headers and body (authorization headers are masked)
- Response status code, headers and body
Log entries are automatically cleaned up by the ir.autovacuum cron job after the configured number of days (default: 30).
Rate Limiting
The module includes built-in rate limiting to protect the server from excessive API usage. Rate limiting is applied per unique combination of IP address and authenticated user ID. When the limit is exceeded the API returns 429 Too Many Requests. Configuration (max requests and window duration) is available under Settings -> API -> Configuration -> Settings. Set the max requests to 0 to disable rate limiting entirely.
Usage
You are able to use the API with a client of your choice or use the client generator as a starting point. For interactive API documentation go to Settings -> API -> Documentation -> Endpoints or navigate directly to /api/docs.
Quick Start Example
The examples below use Basic authentication with admin:admin credentials (Base64-encoded as YWRtaW46YWRtaW4=). Replace the host, credentials and database name with your own values.
Read all partners:
curl -X GET \ 'https://your-odoo.com/api/v2/search_read/res.partner?fields=["name","email"]&limit=5' \ -H 'Authorization: Basic YWRtaW46YWRtaW4=' \ -H 'DATABASE: your-database'
Create a new partner:
curl -X POST \
'https://your-odoo.com/api/v2/create/res.partner' \
-H 'Authorization: Basic YWRtaW46YWRtaW4=' \
-H 'DATABASE: your-database' \
-H 'Content-Type: application/json' \
-d '{"values": {"name": "Jane Doe", "email": "jane@example.com", "is_company": false}}'
Update a partner:
curl -X PUT \
'https://your-odoo.com/api/v2/write/res.partner' \
-H 'Authorization: Basic YWRtaW46YWRtaW4=' \
-H 'DATABASE: your-database' \
-H 'Content-Type: application/json' \
-d '{"ids": [42], "values": {"phone": "+1 555-0123"}}'
Delete a partner:
curl -X DELETE \
'https://your-odoo.com/api/v2/unlink/res.partner' \
-H 'Authorization: Basic YWRtaW46YWRtaW4=' \
-H 'DATABASE: your-database' \
-H 'Content-Type: application/json' \
-d '{"ids": [42]}'
Credit
In this section you will find information about the contributors and maintainers of the app.
Contributors
- Mathias Markl <mathias.markl@mukit.at>
Images
Some pictures are based on or inspired by:
- Font Awesome
- Prosymbols
- Smashicons
Author & Maintainer
This module is maintained by the MuK IT GmbH.
MuK IT is an Austrian company specialized in customizing and extending Odoo. We develop custom solutions for your individual needs to help you focus on your strength and expertise to grow your business.
If you want to get in touch please contact us via mail or visit our website.
MuK Proprietary License v1.0 This software and associated files (the "Software") may only be used (executed, modified, executed after modifications) if you have purchased a valid license from MuK IT GmbH. The above permissions are granted for a single database per purchased license. Furthermore, with a valid license it is permitted to use the software on other databases as long as the usage is limited to a testing or development environment. You may develop modules based on the Software or that use the Software as a library (typically by depending on it, importing it and using its resources), but without copying any source code or material from the Software. You may distribute those modules under the license of your choice, provided that this license is compatible with the terms of the MuK Proprietary License (For example: LGPL, MIT, or proprietary licenses similar to this one). It is forbidden to publish, distribute, sublicense, or sell copies of the Software or modified copies of the Software. The above copyright notice and this permission notice must be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Please log in to comment on this module