diff --git a/requirements.txt b/requirements.txt
index 70c765a0..cc8d360a 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -2,5 +2,7 @@
PyYAML
jsonschema
oauthlib
+openupgradelib
+requests
requests-oauthlib
responses
diff --git a/webservice/README.rst b/webservice/README.rst
index 654941aa..5ed64f60 100644
--- a/webservice/README.rst
+++ b/webservice/README.rst
@@ -35,8 +35,12 @@ WebService
This module creates WebService frameworks to be used globally.
The module introduces support for HTTP Request protocol. The webservice
-HTTP call returns by default the content of the response. A context
-'content_only' can be passed to get the full response object.
+HTTP call returns the full ``requests.Response`` object.
+
+It builds on top of ``webservice_core`` (which provides the
+``webservice.backend`` model with public/username-password/API key
+authentication) to add OAuth2 authentication and ``server_environment``
+support.
**Table of contents**
@@ -86,7 +90,17 @@ endpoint can be configured as:
When a database is neutralized, stored webservice backend credentials
(username, password, API key, OAuth2 client id/secret/token, custom
-OAuth2 auth header value) are cleared.
+OAuth2 auth header value) are cleared. On upgrade from a version prior
+to ``18.0.2.0.1``, a ``webservice.request_content_only`` system
+parameter is created automatically (see that version's migration script)
+to preserve the previous default behavior of HTTP calls, which returned
+only the response content instead of the full ``requests.Response``
+object.
+
+If your code relies on that implicit default, keep the parameter for
+now. Once it's adapted to use the full response object (see *Usage*),
+delete the parameter under *Settings > Technical > System Parameters* -
+new installs never get it set.
Bug Tracker
===========
@@ -129,10 +143,13 @@ promote its widespread use.
.. |maintainer-etobella| image:: https://github.com/etobella.png?size=40px
:target: https://github.com/etobella
:alt: etobella
+.. |maintainer-simahawk| image:: https://github.com/simahawk.png?size=40px
+ :target: https://github.com/simahawk
+ :alt: simahawk
-Current `maintainer `__:
+Current `maintainers `__:
-|maintainer-etobella|
+|maintainer-etobella| |maintainer-simahawk|
This module is part of the `OCA/web-api `_ project on GitHub.
diff --git a/webservice/__init__.py b/webservice/__init__.py
index f64c35ff..6959ecb1 100644
--- a/webservice/__init__.py
+++ b/webservice/__init__.py
@@ -1,3 +1,4 @@
from . import components
from . import models
from . import controllers
+from .hooks import post_init_hook, uninstall_hook
diff --git a/webservice/__manifest__.py b/webservice/__manifest__.py
index b482d8df..2d352aad 100644
--- a/webservice/__manifest__.py
+++ b/webservice/__manifest__.py
@@ -9,14 +9,12 @@
"version": "19.0.1.4.0",
"license": "AGPL-3",
"development_status": "Production/Stable",
- "maintainers": ["etobella"],
+ "maintainers": ["etobella", "simahawk"],
"author": "Creu Blanca, Camptocamp, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web-api",
- "depends": ["component"],
+ "depends": ["webservice_core", "component"],
"external_dependencies": {"python": ["requests-oauthlib", "oauthlib", "responses"]},
"data": [
- "security/ir.model.access.csv",
- "security/ir_rule.xml",
"views/webservice_backend.xml",
],
"demo": [],
diff --git a/webservice/components/request_adapter.py b/webservice/components/request_adapter.py
index 99645343..b733beb2 100644
--- a/webservice/components/request_adapter.py
+++ b/webservice/components/request_adapter.py
@@ -12,8 +12,7 @@
from requests_oauthlib import OAuth2Session
from odoo.addons.component.core import Component
-
-from ..utils import StaticHeaderAuth, sanitize_url_for_log
+from odoo.addons.webservice_core.utils import StaticHeaderAuth, sanitize_url_for_log
_logger = logging.getLogger(__name__)
@@ -26,7 +25,7 @@ class BaseRestRequestsAdapter(Component):
# TODO: url and url_params could come from work_ctx
def _request(self, method, url=None, url_params=None, **kwargs):
url = self._get_url(url=url, url_params=url_params)
- content_only = kwargs.pop("content_only", True)
+ self.collection._pop_deprecated_content_only_kwarg(kwargs)
# TODO: turn on/off debug from webservice setting?
url_to_log = self._sanitize_url_for_log(url)
_logger.info("%s call to %s", method, url_to_log)
@@ -41,7 +40,7 @@ def _request(self, method, url=None, url_params=None, **kwargs):
# pylint: disable=E8106
request = requests.request(method, url, **new_kwargs)
request.raise_for_status()
- if content_only:
+ if self.collection._get_request_content_only():
return request.content
return request
@@ -206,7 +205,7 @@ def _token_fetch_kwargs(self, oauth_params):
def _request(self, method, url=None, url_params=None, **kwargs):
url = self._get_url(url=url, url_params=url_params)
- content_only = kwargs.pop("content_only", True)
+ self.collection._pop_deprecated_content_only_kwarg(kwargs)
new_kwargs = kwargs.copy()
new_kwargs.update(
{
@@ -219,7 +218,7 @@ def _request(self, method, url=None, url_params=None, **kwargs):
# pylint: disable=E8106
request = session.request(method, url, **new_kwargs)
request.raise_for_status()
- if content_only:
+ if self.collection._get_request_content_only():
return request.content
return request
diff --git a/webservice/hooks.py b/webservice/hooks.py
new file mode 100644
index 00000000..a3c3db44
--- /dev/null
+++ b/webservice/hooks.py
@@ -0,0 +1,35 @@
+# Copyright 2025 Camptocamp SA
+# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
+
+from odoo.addons.server_environment.uninstall import restore_env_managed_columns
+
+ENV_MANAGED_FIELDS = [
+ "protocol",
+ "url",
+ "auth_type",
+ "username",
+ "password",
+ "api_key",
+ "api_key_header",
+ "content_type",
+ "oauth2_flow",
+ "oauth2_scope",
+ "oauth2_clientid",
+ "oauth2_client_secret",
+ "oauth2_authorization_url",
+ "oauth2_token_url",
+ "oauth2_audience",
+]
+
+
+def post_init_hook(env):
+ env["webservice.backend"]._preserve_not_env_managed_data(ENV_MANAGED_FIELDS)
+
+
+def uninstall_hook(env):
+ """Restore database columns dropped by server.env.mixin."""
+ restore_env_managed_columns(
+ env,
+ "webservice.backend",
+ ENV_MANAGED_FIELDS,
+ )
diff --git a/webservice/models/webservice_backend.py b/webservice/models/webservice_backend.py
index 3b7f6916..5d1b9aa6 100644
--- a/webservice/models/webservice_backend.py
+++ b/webservice/models/webservice_backend.py
@@ -10,29 +10,26 @@
_logger = logging.getLogger(__name__)
+# Backward-compat switch for the `content_only` default removal on `_request`.
+# Existing databases get it set (see `webservice`'s `18.0.2.0.1` upgrade
+# script) to keep returning only the response content; new installs get the
+# full `requests.Response` object with no param set. Safe to delete once
+# calling code has been adapted; the code checking it can then be dropped
+# too.
+CONTENT_ONLY_COMPAT_PARAM = "webservice.request_content_only"
+
class WebserviceBackend(models.Model):
_name = "webservice.backend"
- _inherit = ["collection.base"]
- _description = "WebService Backend"
+ _inherit = [
+ "webservice.backend",
+ "collection.base",
+ ]
- name = fields.Char(required=True)
- tech_name = fields.Char(required=True)
- protocol = fields.Selection([("http", "HTTP Request")], required=True)
- url = fields.Char(required=True)
auth_type = fields.Selection(
- selection=[
- ("none", "Public"),
- ("user_pwd", "Username & password"),
- ("api_key", "API Key"),
- ("oauth2", "OAuth2"),
- ],
- required=True,
+ selection_add=[("oauth2", "OAuth2")],
+ ondelete={"oauth2": "cascade"},
)
- username = fields.Char(auth_type="user_pwd")
- password = fields.Char(auth_type="user_pwd")
- api_key = fields.Char(string="API Key", auth_type="api_key")
- api_key_header = fields.Char(string="API Key header", auth_type="api_key")
oauth2_flow = fields.Selection(
[
("backend_application", "Backend Application (Client Credentials Grant)"),
@@ -86,30 +83,6 @@ class WebserviceBackend(models.Model):
help="random key generated when authorization flow starts "
"to ensure that no CSRF attack happen"
)
- content_type = fields.Selection(
- [
- ("application/json", "JSON"),
- ("application/xml", "XML"),
- ("application/x-www-form-urlencoded", "Form"),
- ],
- )
- company_id = fields.Many2one("res.company", string="Company")
-
- @api.constrains("auth_type")
- def _check_auth_type(self):
- valid_fields = {
- k: v for k, v in self._fields.items() if hasattr(v, "auth_type")
- }
- for rec in self:
- if rec.auth_type == "none":
- continue
- _fields = [v for v in valid_fields.values() if v.auth_type == rec.auth_type]
- missing = []
- for _field in _fields:
- if not rec[_field.name]:
- missing.append(_field)
- if missing:
- raise exceptions.UserError(rec._msg_missing_auth_param(missing))
@api.constrains(
"auth_type",
@@ -151,22 +124,6 @@ def _check_oauth2_custom_header(self):
if missing:
raise exceptions.UserError(rec._msg_missing_auth_param(missing))
- def _msg_missing_auth_param(self, missing_fields):
- def get_selection_value(fname):
- return self._fields.get(fname).convert_to_export(self[fname], self)
-
- return self.env._(
- "Webservice '%(name)s' requires '%(auth_type)s' authentication. "
- "However, the following field(s) are not valued: %(fields)s",
- name=self.name,
- auth_type=get_selection_value("auth_type"),
- fields=", ".join([f.string for f in missing_fields]),
- )
-
- def _valid_field_parameter(self, field, name):
- extra_params = ("auth_type",)
- return name in extra_params or super()._valid_field_parameter(field, name)
-
@api.onchange("auth_type")
def _onchange_auth_type(self):
# Keep `oauth2_flow` in sync in the UI as the user edits `auth_type`,
@@ -192,6 +149,10 @@ def write(self, vals):
return res
def call(self, method, *args, **kwargs):
+ if not self.auth_type.startswith("oauth2"):
+ return super().call(method, *args, **kwargs)
+ # NOTE: oauth2 still relies on `component` for now, until it gets
+ # extracted to its own module and reworked to drop that dependency too.
_logger.debug("backend %s: call %s %s %s", self.name, method, args, kwargs)
response = getattr(self._get_adapter(), method)(*args, **kwargs)
_logger.debug("backend %s: response: \n%s", self.name, response)
@@ -204,6 +165,50 @@ def _get_adapter(self):
webservice_protocol=self._get_adapter_protocol(),
)
+ def _request(self, method, url=None, url_params=None, **kwargs):
+ self._pop_deprecated_content_only_kwarg(kwargs)
+ response = super()._request(method, url=url, url_params=url_params, **kwargs)
+ if self._get_request_content_only():
+ return response.content
+ return response
+
+ def _pop_deprecated_content_only_kwarg(self, kwargs):
+ """Drop the removed ``content_only`` call argument, warning if used.
+
+ It used to switch between returning the raw response content or the
+ full ``requests.Response`` object per call. It's gone: the full
+ response is always returned now, controlled only (and temporarily)
+ by the ``CONTENT_ONLY_COMPAT_PARAM`` system parameter for the whole
+ database - not something to keep sprinkling through call sites.
+ """
+ if "content_only" in kwargs:
+ kwargs.pop("content_only")
+ _logger.warning(
+ "%s: the 'content_only' argument is no longer supported "
+ "and was ignored; the full response object is always "
+ "returned now. Remove it from the calling code.",
+ self.display_name,
+ )
+
+ def _get_request_content_only(self):
+ """Whether to return only the response content (legacy behavior).
+
+ See ``CONTENT_ONLY_COMPAT_PARAM``.
+ """
+ content_only = bool(
+ self.env["ir.config_parameter"].sudo().get_param(CONTENT_ONLY_COMPAT_PARAM)
+ )
+ if content_only:
+ _logger.warning(
+ "%s: returning only the response content because the "
+ "'%s' system parameter is set (kept for backward "
+ "compatibility after upgrade). Delete it once the calling "
+ "code is adapted to use the full response object.",
+ self.display_name,
+ CONTENT_ONLY_COMPAT_PARAM,
+ )
+ return content_only
+
def _get_adapter_protocol(self):
protocol = self.protocol
if self.auth_type.startswith("oauth2"):
diff --git a/webservice/readme/CONFIGURE.md b/webservice/readme/CONFIGURE.md
index 4cd9ccc6..e5818fa3 100644
--- a/webservice/readme/CONFIGURE.md
+++ b/webservice/readme/CONFIGURE.md
@@ -33,3 +33,13 @@ configured as:
When a database is neutralized, stored webservice backend credentials
(username, password, API key, OAuth2 client id/secret/token, custom
OAuth2 auth header value) are cleared.
+On upgrade from a version prior to `18.0.2.0.1`, a
+`webservice.request_content_only` system parameter is created automatically
+(see that version's migration script) to preserve the previous default
+behavior of HTTP calls, which returned only the response content instead of
+the full `requests.Response` object.
+
+If your code relies on that implicit default, keep the parameter for now.
+Once it's adapted to use the full response object (see *Usage*), delete the
+parameter under *Settings > Technical > System Parameters* - new installs
+never get it set.
diff --git a/webservice/readme/DESCRIPTION.md b/webservice/readme/DESCRIPTION.md
index cdd44bd7..74b608df 100644
--- a/webservice/readme/DESCRIPTION.md
+++ b/webservice/readme/DESCRIPTION.md
@@ -1,3 +1,7 @@
This module creates WebService frameworks to be used globally.
-The module introduces support for HTTP Request protocol. The webservice HTTP call returns by default the content of the response. A context 'content_only' can be passed to get the full response object.
+The module introduces support for HTTP Request protocol. The webservice HTTP call returns the full `requests.Response` object.
+
+It builds on top of ``webservice_core`` (which provides the ``webservice.backend``
+model with public/username-password/API key authentication) to add OAuth2
+authentication and ``server_environment`` support.
diff --git a/webservice/static/description/index.html b/webservice/static/description/index.html
index 32e0b279..fab0af4b 100644
--- a/webservice/static/description/index.html
+++ b/webservice/static/description/index.html
@@ -377,8 +377,11 @@
WebService
This module creates WebService frameworks to be used globally.
The module introduces support for HTTP Request protocol. The webservice
-HTTP call returns by default the content of the response. A context
-‘content_only’ can be passed to get the full response object.
+HTTP call returns the full requests.Response object.
+
It builds on top of webservice_core (which provides the
+webservice.backend model with public/username-password/API key
+authentication) to add OAuth2 authentication and server_environment
+support.
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
diff --git a/webservice/tests/__init__.py b/webservice/tests/__init__.py
index 88a07b8f..37c85ace 100644
--- a/webservice/tests/__init__.py
+++ b/webservice/tests/__init__.py
@@ -1,4 +1,2 @@
+from . import test_content_only_compat
from . import test_oauth2
-from . import test_webservice
-from . import test_utils
-from . import test_neutralize
diff --git a/webservice/tests/test_content_only_compat.py b/webservice/tests/test_content_only_compat.py
new file mode 100644
index 00000000..3552ebed
--- /dev/null
+++ b/webservice/tests/test_content_only_compat.py
@@ -0,0 +1,64 @@
+# Copyright 2026 Camptocamp SA
+# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
+import responses
+
+from .common import CommonWebService
+
+
+class TestContentOnlyCompat(CommonWebService):
+ """`content_only` removal, and its backward-compat system parameter.
+
+ This lives in `webservice`, not `webservice_core`: the compat switch
+ only matters for databases that already ran with the old
+ `content_only=True` default, and that's `webservice`'s history, not
+ `webservice_core`'s (a new, not-yet-released module nobody depends on
+ with that old default).
+ """
+
+ @classmethod
+ def _setup_records(cls):
+ res = super()._setup_records()
+ cls.url = "https://localhost.demo.odoo/"
+ cls.webservice = cls.env["webservice.backend"].create(
+ {
+ "name": "WebService",
+ "protocol": "http",
+ "url": cls.url,
+ "tech_name": "demo_ws_content_only",
+ "auth_type": "none",
+ }
+ )
+ return res
+
+ @responses.activate
+ def test_returns_full_response_by_default(self):
+ responses.add(responses.GET, self.url, body="{}")
+ result = self.webservice.call("get")
+ self.assertEqual(result.content, b"{}")
+ self.assertEqual(result.status_code, 200)
+
+ @responses.activate
+ def test_compat_param_restores_content_only(self):
+ self.env["ir.config_parameter"].sudo().set_param(
+ "webservice.request_content_only", "1"
+ )
+ responses.add(responses.GET, self.url, body="{}")
+ with self.assertLogs(
+ "odoo.addons.webservice.models.webservice_backend", level="WARNING"
+ ) as log_catcher:
+ result = self.webservice.call("get")
+ self.assertEqual(result, b"{}")
+ self.assertTrue(
+ any("webservice.request_content_only" in m for m in log_catcher.output)
+ )
+
+ @responses.activate
+ def test_content_only_kwarg_is_ignored(self):
+ """The removed `content_only` kwarg no longer has any effect."""
+ responses.add(responses.GET, self.url, body="{}")
+ with self.assertLogs(
+ "odoo.addons.webservice.models.webservice_backend", level="WARNING"
+ ) as log_catcher:
+ result = self.webservice.call("get", content_only=True)
+ self.assertEqual(result.content, b"{}")
+ self.assertTrue(any("content_only" in m for m in log_catcher.output))
diff --git a/webservice/tests/test_oauth2.py b/webservice/tests/test_oauth2.py
index 1288cda8..5187edb1 100644
--- a/webservice/tests/test_oauth2.py
+++ b/webservice/tests/test_oauth2.py
@@ -70,7 +70,7 @@ def test_fetch_token(self):
delta=1, # Accept a diff of 1s
)
self.assertEqual(responses.calls[1].response.content.decode(), "OK")
- self.assertEqual(result.decode(), "OK")
+ self.assertEqual(result.content.decode(), "OK")
@responses.activate
def test_update_token(self):
@@ -112,7 +112,7 @@ def test_update_token(self):
delta=1, # Accept a diff of 1s
)
self.assertEqual(responses.calls[1].response.content.decode(), "OK")
- self.assertEqual(result.decode(), "OK")
+ self.assertEqual(result.content.decode(), "OK")
@responses.activate
def test_update_token_with_error(self):
diff --git a/webservice/upgrades/18.0.1.1.1/post-update.py b/webservice/upgrades/18.0.1.1.1/post-update.py
new file mode 100644
index 00000000..c0fce93f
--- /dev/null
+++ b/webservice/upgrades/18.0.1.1.1/post-update.py
@@ -0,0 +1,22 @@
+# Copyright 2026 Camptocamp SA
+# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
+
+from openupgradelib import openupgrade
+
+from odoo import exceptions
+
+
+@openupgrade.migrate()
+def migrate(env, version):
+ module = env["ir.module.module"].search([("name", "=", "webservice_server_env")])
+ if not module:
+ raise exceptions.UserError(
+ env._(
+ "The 'webservice_server_env' module is not available. "
+ "It is required to preserve the server environment managed "
+ "fields of 'webservice.backend'. Make it available on the "
+ "addons path before upgrading 'webservice'."
+ )
+ )
+ if module.state == "uninstalled":
+ module.button_install()
diff --git a/webservice/upgrades/18.0.2.0.1/post-update.py b/webservice/upgrades/18.0.2.0.1/post-update.py
new file mode 100644
index 00000000..5c1f3f42
--- /dev/null
+++ b/webservice/upgrades/18.0.2.0.1/post-update.py
@@ -0,0 +1,24 @@
+# Copyright 2026 Camptocamp SA
+# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
+
+from openupgradelib import openupgrade
+
+CONTENT_ONLY_COMPAT_PARAM = "webservice.request_content_only"
+
+
+@openupgrade.migrate()
+def migrate(env, version):
+ """Preserve the pre-upgrade behavior of HTTP webservice calls.
+
+ Before this version, ``webservice.backend.call()`` (and friends)
+ returned only the response content (raw bytes) by default. That default
+ is gone: calls now always return the full ``requests.Response`` object.
+
+ Existing databases get ``CONTENT_ONLY_COMPAT_PARAM`` set so their
+ calling code keeps working unchanged until it's adapted; new installs
+ never get it, so they see the new behavior right away. Leave the
+ parameter unset (or delete it) once the calling code is updated.
+ """
+ icp = env["ir.config_parameter"].sudo()
+ if not icp.search_count([("key", "=", CONTENT_ONLY_COMPAT_PARAM)]):
+ icp.set_param(CONTENT_ONLY_COMPAT_PARAM, "1")
diff --git a/webservice/views/webservice_backend.xml b/webservice/views/webservice_backend.xml
index 6b398d92..7c401162 100644
--- a/webservice/views/webservice_backend.xml
+++ b/webservice/views/webservice_backend.xml
@@ -3,167 +3,55 @@
License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). -->
- webservice.backend.form (in webservice)
+ webservice.backend.form (oauth2, in webservice)webservice.backend
+
-
-
-
-
-
- webservice.backend.search (in webservice)
- webservice.backend
-
-
-
-
-
-
-
-
-
-
-
- webservice.backend.tree (in webservice)
- webservice.backend
-
-
-
-
-
-
+
+
+
+
-
+
+
+
+
+
+
+
+
-
-
- WebService Backend
- webservice.backend
- list,form
- []
- {}
-
-
-
- WebService Backend
-
-
-
-
diff --git a/webservice_core/README.rst b/webservice_core/README.rst
new file mode 100644
index 00000000..81edd6f9
--- /dev/null
+++ b/webservice_core/README.rst
@@ -0,0 +1,180 @@
+.. image:: https://odoo-community.org/readme-banner-image
+ :target: https://odoo-community.org/get-involved?utm_source=readme
+ :alt: Odoo Community Association
+
+===============
+WebService Core
+===============
+
+..
+ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ !! This file is generated by oca-gen-addon-readme !!
+ !! changes will be overwritten. !!
+ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ !! source digest: sha256:2fc3afa9011aae31e4b0d0a46e9f061c1faa70cb1a705cec07bea68c5cb7f54b
+ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+.. |badge1| image:: https://img.shields.io/badge/maturity-Production%2FStable-green.png
+ :target: https://odoo-community.org/page/development-status
+ :alt: Production/Stable
+.. |badge2| image:: https://img.shields.io/badge/license-AGPL--3-blue.png
+ :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
+ :alt: License: AGPL-3
+.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb--api-lightgray.png?logo=github
+ :target: https://github.com/OCA/web-api/tree/19.0/webservice_core
+ :alt: OCA/web-api
+.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
+ :target: https://translation.odoo-community.org/projects/web-api-19-0/web-api-19-0-webservice_core
+ :alt: Translate me on Weblate
+.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
+ :target: https://runboat.odoo-community.org/builds?repo=OCA/web-api&target_branch=19.0
+ :alt: Try me on Runboat
+
+|badge1| |badge2| |badge3| |badge4| |badge5|
+
+This module provides the ``webservice.backend`` model with its
+authentication (public, username/password, API key) and HTTP call
+features (``get``/``post``/``put``).
+
+It has no dependency on ``component`` or ``server_environment``, so it
+can be used as a lightweight building block by any module needing to
+configure and call an outbound webservice, without pulling in extra
+frameworks.
+
+**Table of contents**
+
+.. contents::
+ :local:
+
+Configuration
+=============
+
+Go to *Settings > Technical > WebService Backend* (requires the
+*Administration / Settings* group) and create a new backend:
+
+- **Name** / **Technical Name**: a label and a unique technical key
+ you'll use to look the backend up from code (e.g. ``env.ref`` is not
+ used here; search by ``tech_name`` instead).
+- **Protocol**: only ``HTTP Request`` is available in this module.
+- **URL**: the base URL every call is relative to, e.g.
+ ``https://api.example.com``. It may contain ``{placeholder}`` tokens
+ (see *Usage*), e.g. ``https://api.example.com/{endpoint}``.
+- **Content-Type**: optional default ``Content-Type`` header for every
+ call.
+
+Then configure authentication via **Auth Type**:
+
+- **Public**: no credentials needed.
+- **Username & password**: sent as HTTP Basic Auth. Requires
+ **Username** and **Password**.
+- **API Key**: sent as a custom header. Requires **API Key** and **API
+ Key header** (the header name to send it under, e.g. ``X-Api-Key``).
+
+Required fields depend on the selected auth type; the form only shows
+and requires the ones that apply, and saving enforces it.
+
+Usage
+=====
+
+Look up the backend (e.g. by its technical name) and call it:
+
+.. code:: python
+
+ backend = env["webservice.backend"].search([("tech_name", "=", "my_api")])
+ result = backend.call("get") # -> requests.Response
+ result.content
+ result.status_code
+
+``call(method, *args, **kwargs)`` accepts any of the standard HTTP verbs
+(``get``, ``post``, ``put``, ``delete``) and forwards everything else to
+`requests `__, so any of its keyword
+arguments work too (``data``, ``json``, ``params``, ``files``, ...):
+
+.. code:: python
+
+ backend.call("post", data=b"...")
+ backend.call("post", json={"foo": "bar"})
+
+**URL**: by default the backend's own ``url`` is used. Pass ``url`` to
+hit a different path - relative paths are appended to the backend's URL,
+a full ``http(s)://`` URL is used as-is:
+
+.. code:: python
+
+ backend.call("get", url="orders") # -> /orders
+ backend.call("get", url="https://other.example.com/orders")
+
+If the backend's URL (or the ``url`` passed above) contains
+``{placeholder}`` tokens, fill them with ``url_params``:
+
+.. code:: python
+
+ # backend.url == "https://api.example.com/{endpoint}"
+ backend.call("get", url_params={"endpoint": "orders"})
+
+**Headers**: pass ``headers`` to add/override headers for that call;
+they are merged on top of the backend's own ``Content-Type`` and
+auth-derived headers (e.g. the API key header):
+
+.. code:: python
+
+ backend.call("get", headers={"X-Request-Id": "42"})
+
+**Auth override**: pass ``auth`` to bypass the backend's configured auth
+type for a single call (same format ``requests`` itself accepts, e.g. a
+``(user, password)`` tuple):
+
+.. code:: python
+
+ backend.call("get", auth=("other_user", "other_password"))
+
+Bug Tracker
+===========
+
+Bugs are tracked on `GitHub Issues `_.
+In case of trouble, please check there if your issue has already been reported.
+If you spotted it first, help us to smash it by providing a detailed and welcomed
+`feedback `_.
+
+Do not contact contributors directly about support or help with technical issues.
+
+Credits
+=======
+
+Authors
+-------
+
+* Creu Blanca
+* Camptocamp
+
+Contributors
+------------
+
+- Simone Orsi
+- Enric Tobella
+- Alexandre Fayolle
+
+Maintainers
+-----------
+
+This module is maintained by the OCA.
+
+.. image:: https://odoo-community.org/logo.png
+ :alt: Odoo Community Association
+ :target: https://odoo-community.org
+
+OCA, or the Odoo Community Association, is a nonprofit organization whose
+mission is to support the collaborative development of Odoo features and
+promote its widespread use.
+
+.. |maintainer-simahawk| image:: https://github.com/simahawk.png?size=40px
+ :target: https://github.com/simahawk
+ :alt: simahawk
+
+Current `maintainer `__:
+
+|maintainer-simahawk|
+
+This module is part of the `OCA/web-api `_ project on GitHub.
+
+You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
diff --git a/webservice_core/__init__.py b/webservice_core/__init__.py
new file mode 100644
index 00000000..6d58305f
--- /dev/null
+++ b/webservice_core/__init__.py
@@ -0,0 +1,2 @@
+from . import models
+from .hooks import pre_init_hook
diff --git a/webservice_core/__manifest__.py b/webservice_core/__manifest__.py
new file mode 100644
index 00000000..8c818a3d
--- /dev/null
+++ b/webservice_core/__manifest__.py
@@ -0,0 +1,22 @@
+# Copyright 2020 Creu Blanca
+# Copyright 2022 Camptocamp SA
+# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
+
+{
+ "name": "WebService Core",
+ "summary": """Webservice backend: auth & call features, no extra dependencies""",
+ "version": "19.0.1.0.0",
+ "license": "AGPL-3",
+ "development_status": "Production/Stable",
+ "maintainers": ["simahawk"],
+ "author": "Creu Blanca, Camptocamp, Odoo Community Association (OCA)",
+ "website": "https://github.com/OCA/web-api",
+ "depends": ["base"],
+ "external_dependencies": {"python": ["requests", "openupgradelib"]},
+ "data": [
+ "security/ir.model.access.csv",
+ "security/ir_rule.xml",
+ "views/webservice_backend.xml",
+ ],
+ "pre_init_hook": "pre_init_hook",
+}
diff --git a/webservice_core/hooks.py b/webservice_core/hooks.py
new file mode 100644
index 00000000..52a5f8ab
--- /dev/null
+++ b/webservice_core/hooks.py
@@ -0,0 +1,26 @@
+# Copyright 2026 Camptocamp SA
+# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
+from openupgradelib import openupgrade
+
+# `webservice.backend`'s base access rule, multi-company rule, and
+# non-form views (search/list/action/menu) used to be defined by
+# `webservice`, before this module split the base backend out of it. The
+# form view keeps its own `webservice.webservice_backend_form_view` XMLID
+# (its content changed, but `webservice` still owns and extends it), so it
+# is deliberately not in this list.
+MOVED_XMLIDS = [
+ "access_webservice_backend_edit",
+ "rule_webservice_backend_multi_company",
+ "webservice_backend_search_view",
+ "webservice_backend_tree_view",
+ "webservice_backend_act_window",
+ "webservice_backend_menu",
+]
+
+
+def pre_init_hook(env):
+ """Reuse `webservice`'s pre-split records instead of duplicating them."""
+ openupgrade.rename_xmlids(
+ env.cr,
+ [(f"webservice.{xmlid}", f"webservice_core.{xmlid}") for xmlid in MOVED_XMLIDS],
+ )
diff --git a/webservice_core/models/__init__.py b/webservice_core/models/__init__.py
new file mode 100644
index 00000000..5b6cd501
--- /dev/null
+++ b/webservice_core/models/__init__.py
@@ -0,0 +1,2 @@
+from . import webservice_request_mixin
+from . import webservice_backend
diff --git a/webservice_core/models/webservice_backend.py b/webservice_core/models/webservice_backend.py
new file mode 100644
index 00000000..fde3125a
--- /dev/null
+++ b/webservice_core/models/webservice_backend.py
@@ -0,0 +1,19 @@
+# Copyright 2020 Creu Blanca
+# Copyright 2022 Camptocamp SA
+# @author Simone Orsi
+# @author Alexandre Fayolle
+# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
+from odoo import fields, models
+
+
+class WebserviceBackend(models.Model):
+ _name = "webservice.backend"
+ _inherit = ["webservice.request.mixin"]
+ _description = "WebService Backend"
+
+ name = fields.Char(required=True)
+ url = fields.Char(required=True)
+ company_id = fields.Many2one("res.company", string="Company")
+
+ def _get_base_url(self):
+ return self.url
diff --git a/webservice_core/models/webservice_request_mixin.py b/webservice_core/models/webservice_request_mixin.py
new file mode 100644
index 00000000..301d3a1a
--- /dev/null
+++ b/webservice_core/models/webservice_request_mixin.py
@@ -0,0 +1,230 @@
+# Copyright 2020 Creu Blanca
+# Copyright 2022 Camptocamp SA
+# @author Simone Orsi
+# @author Alexandre Fayolle
+# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
+import logging
+
+import requests
+
+from odoo import api, exceptions, fields, models
+
+from ..utils import sanitize_url_for_log
+
+_logger = logging.getLogger(__name__)
+
+
+class WebserviceRequestMixin(models.AbstractModel):
+ """Auth configuration + HTTP call features for any webservice-like record.
+
+ Any model inheriting this mixin becomes able to issue authenticated HTTP
+ requests based on its own ``auth_type``/credential fields, resolved via
+ ``self._get_base_url()`` which must be implemented by the model.
+
+ ``call()`` dispatches by ``self._get_protocol()`` (``self.protocol`` by
+ default) to a ``_handle_call_for_`` method that actually
+ performs the request - ``_handle_call_for_http`` today. A new protocol is
+ added by implementing a new ``_handle_call_for_``.
+
+ Extra auth types are added by other modules via plain model inheritance:
+ add the new value to the ``auth_type`` selection, add fields tagged with
+ the matching ``auth_type=`` parameter, and implement
+ ``_get_auth_for_``/``_get_headers_for_`` and/or override
+ ``_request`` when the whole HTTP request flow needs to change (e.g.
+ oauth2).
+ """
+
+ _name = "webservice.request.mixin"
+ _description = "Webservice Request Mixin"
+ tech_name = fields.Char(
+ required=True,
+ copy=False,
+ help="Unique name for technical purposes. "
+ "Automatically generated from the name if left empty.",
+ )
+ protocol = fields.Selection([("http", "HTTP Request")], required=True)
+ auth_type = fields.Selection(
+ selection=[
+ ("none", "Public"),
+ ("user_pwd", "Username & password"),
+ ("api_key", "API Key"),
+ ],
+ required=True,
+ )
+ username = fields.Char(auth_type="user_pwd")
+ password = fields.Char(auth_type="user_pwd")
+ api_key = fields.Char(string="API Key", auth_type="api_key")
+ api_key_header = fields.Char(string="API Key header", auth_type="api_key")
+ content_type = fields.Selection(
+ [
+ ("application/json", "JSON"),
+ ("application/xml", "XML"),
+ ("application/x-www-form-urlencoded", "Form"),
+ ],
+ )
+
+ _tech_name_uniq = models.Constraint(
+ "unique(tech_name)",
+ "`tech_name` must be unique!",
+ )
+
+ @api.constrains("auth_type")
+ def _check_auth_type(self):
+ valid_fields = {
+ k: v for k, v in self._fields.items() if hasattr(v, "auth_type")
+ }
+ for rec in self:
+ if rec.auth_type == "none":
+ continue
+ _fields = [v for v in valid_fields.values() if v.auth_type == rec.auth_type]
+ missing = []
+ for _field in _fields:
+ if not rec[_field.name]:
+ missing.append(_field)
+ if missing:
+ raise exceptions.UserError(rec._msg_missing_auth_param(missing))
+
+ def _msg_missing_auth_param(self, missing_fields):
+ def get_selection_value(fname):
+ return self._fields.get(fname).convert_to_export(self[fname], self)
+
+ return self.env._(
+ "Webservice '%(name)s' requires '%(auth_type)s' authentication. "
+ "However, the following field(s) are not valued: %(fields)s",
+ name=self.name,
+ auth_type=get_selection_value("auth_type"),
+ fields=", ".join([f.string for f in missing_fields]),
+ )
+
+ def _valid_field_parameter(self, field, name):
+ extra_params = ("auth_type",)
+ return name in extra_params or super()._valid_field_parameter(field, name)
+
+ @api.onchange("name")
+ def _onchange_name_for_tech_name(self):
+ # Keep this specific name for the method to avoid possible overrides
+ # of existing `_onchange_name` methods
+ if self.name and not self.tech_name:
+ self.tech_name = self.name
+
+ @api.onchange("tech_name")
+ def _onchange_tech_name(self):
+ if self.tech_name:
+ # make sure it's normalized
+ self.tech_name = self._normalize_tech_name(self.tech_name)
+
+ @api.model_create_multi
+ def create(self, vals_list):
+ for vals in vals_list:
+ self._handle_tech_name(vals)
+ return super().create(vals_list)
+
+ def write(self, vals):
+ self._handle_tech_name(vals)
+ return super().write(vals)
+
+ def _handle_tech_name(self, vals):
+ # make sure technical names are always there
+ if not vals.get("tech_name") and vals.get("name"):
+ vals["tech_name"] = self._normalize_tech_name(vals["name"])
+
+ def _normalize_tech_name(self, name):
+ return self.env["ir.http"]._slugify(name).replace("-", "_")
+
+ def call(self, method, *args, **kwargs):
+ _logger.debug("%s: call %s %s %s", self.display_name, method, args, kwargs)
+ handler = getattr(self, "_handle_call_for_" + self._get_protocol())
+ response = handler(method, *args, **kwargs)
+ _logger.debug("%s: response: \n%s", self.display_name, response)
+ return response
+
+ def _get_protocol(self):
+ return self.protocol
+
+ def _handle_call_for_http(self, method, **kwargs):
+ return self._request(method, **kwargs)
+
+ # shortcuts
+ def call_get(self, **kwargs):
+ return self.call("get", **kwargs)
+
+ def call_post(self, **kwargs):
+ return self.call("post", **kwargs)
+
+ def call_put(self, **kwargs):
+ return self.call("put", **kwargs)
+
+ def call_delete(self, **kwargs):
+ return self.call("delete", **kwargs)
+
+ def _request(self, method, url=None, url_params=None, **kwargs):
+ url = self._get_url(url=url, url_params=url_params)
+ url_to_log = self._sanitize_url_for_log(url)
+ _logger.info("%s call to %s", method, url_to_log)
+ new_kwargs = kwargs.copy()
+ new_kwargs.update(
+ {
+ "auth": self._get_auth(**kwargs),
+ "headers": self._get_headers(**kwargs),
+ # TODO: no timeout is enforced here (requests would wait forever).
+ # Consider adding configurable connect/read timeout fields.
+ "timeout": None,
+ }
+ )
+ # pylint: disable=E8106
+ request = requests.request(method, url, **new_kwargs)
+ request.raise_for_status()
+ return request
+
+ def _sanitize_url_for_log(self, url):
+ return sanitize_url_for_log(url)
+
+ def _get_auth(self, auth=False, **kwargs):
+ if auth:
+ return auth
+ handler = getattr(self, "_get_auth_for_" + self.auth_type, None)
+ return handler(**kwargs) if handler else None
+
+ def _get_auth_for_user_pwd(self, **kw):
+ if self.username and self.password:
+ return self.username, self.password
+ return None
+
+ def _get_headers(self, content_type=False, headers=False, **kwargs):
+ headers = headers or {}
+ if content_type or self.content_type:
+ result = {
+ "Content-Type": content_type or self.content_type,
+ }
+ else:
+ result = {}
+ handler = getattr(self, "_get_headers_for_" + self.auth_type, None)
+ if handler:
+ headers.update(handler(**kwargs))
+ result.update(headers)
+ return result
+
+ def _get_headers_for_api_key(self, **kw):
+ return {self.api_key_header: self.api_key}
+
+ def _get_url(self, url=None, url_params=None, **kwargs):
+ base = self._get_base_url()
+ if not url:
+ url = base
+ elif not url.startswith(base):
+ if not url.startswith("http"):
+ url = f"{base.rstrip('/')}/{url.lstrip('/')}"
+ else:
+ # TODO: if url is given, we should validate the domain
+ # to avoid abusing a webservice backend for different calls.
+ pass
+
+ url_params = url_params or kwargs
+ return url.format(**url_params)
+
+ def _get_base_url(self):
+ """Return the base url requests are relative to.
+
+ To be implemented by models inheriting this mixin.
+ """
+ raise NotImplementedError
diff --git a/webservice_core/pyproject.toml b/webservice_core/pyproject.toml
new file mode 100644
index 00000000..4231d0cc
--- /dev/null
+++ b/webservice_core/pyproject.toml
@@ -0,0 +1,3 @@
+[build-system]
+requires = ["whool"]
+build-backend = "whool.buildapi"
diff --git a/webservice_core/readme/CONFIGURE.md b/webservice_core/readme/CONFIGURE.md
new file mode 100644
index 00000000..1c71d644
--- /dev/null
+++ b/webservice_core/readme/CONFIGURE.md
@@ -0,0 +1,22 @@
+Go to *Settings > Technical > WebService Backend* (requires the
+*Administration / Settings* group) and create a new backend:
+
+- **Name** / **Technical Name**: a label and a unique technical key you'll
+ use to look the backend up from code (e.g. `env.ref` is not used here;
+ search by `tech_name` instead).
+- **Protocol**: only `HTTP Request` is available in this module.
+- **URL**: the base URL every call is relative to, e.g.
+ `https://api.example.com`. It may contain `{placeholder}` tokens (see
+ *Usage*), e.g. `https://api.example.com/{endpoint}`.
+- **Content-Type**: optional default `Content-Type` header for every call.
+
+Then configure authentication via **Auth Type**:
+
+- **Public**: no credentials needed.
+- **Username & password**: sent as HTTP Basic Auth. Requires **Username**
+ and **Password**.
+- **API Key**: sent as a custom header. Requires **API Key** and
+ **API Key header** (the header name to send it under, e.g. `X-Api-Key`).
+
+Required fields depend on the selected auth type; the form only shows and
+requires the ones that apply, and saving enforces it.
diff --git a/webservice_core/readme/CONTRIBUTORS.md b/webservice_core/readme/CONTRIBUTORS.md
new file mode 100644
index 00000000..d0412679
--- /dev/null
+++ b/webservice_core/readme/CONTRIBUTORS.md
@@ -0,0 +1,3 @@
+- Simone Orsi \<\>
+- Enric Tobella \<\>
+- Alexandre Fayolle \<\>
diff --git a/webservice_core/readme/DESCRIPTION.md b/webservice_core/readme/DESCRIPTION.md
new file mode 100644
index 00000000..bfae3ae6
--- /dev/null
+++ b/webservice_core/readme/DESCRIPTION.md
@@ -0,0 +1,7 @@
+This module provides the ``webservice.backend`` model with its authentication
+(public, username/password, API key) and HTTP call features (``get``/``post``/``put``).
+
+It has no dependency on ``component`` or ``server_environment``, so it can be used
+as a lightweight building block by any module needing to configure and call
+an outbound webservice, without pulling in extra frameworks.
+
diff --git a/webservice_core/readme/USAGE.md b/webservice_core/readme/USAGE.md
new file mode 100644
index 00000000..b767124e
--- /dev/null
+++ b/webservice_core/readme/USAGE.md
@@ -0,0 +1,52 @@
+Look up the backend (e.g. by its technical name) and call it:
+
+```python
+backend = env["webservice.backend"].search([("tech_name", "=", "my_api")])
+result = backend.call("get") # -> requests.Response
+result.content
+result.status_code
+```
+
+`call(method, *args, **kwargs)` accepts any of the standard HTTP verbs
+(`get`, `post`, `put`, `delete`) and forwards everything else to
+[requests](https://requests.readthedocs.io/), so any of its keyword
+arguments work too (`data`, `json`, `params`, `files`, ...):
+
+```python
+backend.call("post", data=b"...")
+backend.call("post", json={"foo": "bar"})
+```
+
+**URL**: by default the backend's own `url` is used. Pass `url` to hit a
+different path - relative paths are appended to the backend's URL, a full
+`http(s)://` URL is used as-is:
+
+```python
+backend.call("get", url="orders") # -> /orders
+backend.call("get", url="https://other.example.com/orders")
+```
+
+If the backend's URL (or the `url` passed above) contains `{placeholder}`
+tokens, fill them with `url_params`:
+
+```python
+# backend.url == "https://api.example.com/{endpoint}"
+backend.call("get", url_params={"endpoint": "orders"})
+```
+
+**Headers**: pass `headers` to add/override headers for that call; they are
+merged on top of the backend's own `Content-Type` and auth-derived headers
+(e.g. the API key header):
+
+```python
+backend.call("get", headers={"X-Request-Id": "42"})
+```
+
+**Auth override**: pass `auth` to bypass the backend's configured auth type
+for a single call (same format `requests` itself accepts, e.g. a
+`(user, password)` tuple):
+
+```python
+backend.call("get", auth=("other_user", "other_password"))
+```
+
diff --git a/webservice/security/ir.model.access.csv b/webservice_core/security/ir.model.access.csv
similarity index 100%
rename from webservice/security/ir.model.access.csv
rename to webservice_core/security/ir.model.access.csv
diff --git a/webservice/security/ir_rule.xml b/webservice_core/security/ir_rule.xml
similarity index 100%
rename from webservice/security/ir_rule.xml
rename to webservice_core/security/ir_rule.xml
diff --git a/webservice_core/static/description/icon.png b/webservice_core/static/description/icon.png
new file mode 100644
index 00000000..3a0328b5
Binary files /dev/null and b/webservice_core/static/description/icon.png differ
diff --git a/webservice_core/static/description/index.html b/webservice_core/static/description/index.html
new file mode 100644
index 00000000..234885ab
--- /dev/null
+++ b/webservice_core/static/description/index.html
@@ -0,0 +1,511 @@
+
+
+
+
+
+README.rst
+
+
+
+
This module provides the webservice.backend model with its
+authentication (public, username/password, API key) and HTTP call
+features (get/post/put).
+
It has no dependency on component or server_environment, so it
+can be used as a lightweight building block by any module needing to
+configure and call an outbound webservice, without pulling in extra
+frameworks.
Go to Settings > Technical > WebService Backend (requires the
+Administration / Settings group) and create a new backend:
+
+
Name / Technical Name: a label and a unique technical key
+you’ll use to look the backend up from code (e.g. env.ref is not
+used here; search by tech_name instead).
+
Protocol: only HTTP Request is available in this module.
+
URL: the base URL every call is relative to, e.g.
+https://api.example.com. It may contain {placeholder} tokens
+(see Usage), e.g. https://api.example.com/{endpoint}.
+
Content-Type: optional default Content-Type header for every
+call.
+
+
Then configure authentication via Auth Type:
+
+
Public: no credentials needed.
+
Username & password: sent as HTTP Basic Auth. Requires
+Username and Password.
+
API Key: sent as a custom header. Requires API Key and API
+Key header (the header name to send it under, e.g. X-Api-Key).
+
+
Required fields depend on the selected auth type; the form only shows
+and requires the ones that apply, and saving enforces it.
call(method, *args, **kwargs) accepts any of the standard HTTP verbs
+(get, post, put, delete) and forwards everything else to
+requests, so any of its keyword
+arguments work too (data, json, params, files, …):
URL: by default the backend’s own url is used. Pass url to
+hit a different path - relative paths are appended to the backend’s URL,
+a full http(s):// URL is used as-is:
Headers: pass headers to add/override headers for that call;
+they are merged on top of the backend’s own Content-Type and
+auth-derived headers (e.g. the API key header):
Auth override: pass auth to bypass the backend’s configured auth
+type for a single call (same format requests itself accepts, e.g. a
+(user, password) tuple):
Bugs are tracked on GitHub Issues.
+In case of trouble, please check there if your issue has already been reported.
+If you spotted it first, help us to smash it by providing a detailed and welcomed
+feedback.
+
Do not contact contributors directly about support or help with technical issues.
OCA, or the Odoo Community Association, is a nonprofit organization whose
+mission is to support the collaborative development of Odoo features and
+promote its widespread use.