Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
PyYAML
jsonschema
oauthlib
openupgradelib
requests
requests-oauthlib
responses
27 changes: 22 additions & 5 deletions webservice/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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**

Expand Down Expand Up @@ -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
===========
Expand Down Expand Up @@ -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 <https://odoo-community.org/page/maintainer-role>`__:
Current `maintainers <https://odoo-community.org/page/maintainer-role>`__:

|maintainer-etobella|
|maintainer-etobella| |maintainer-simahawk|

This module is part of the `OCA/web-api <https://github.com/OCA/web-api/tree/19.0/webservice>`_ project on GitHub.

Expand Down
1 change: 1 addition & 0 deletions webservice/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from . import components
from . import models
from . import controllers
from .hooks import post_init_hook, uninstall_hook
6 changes: 2 additions & 4 deletions webservice/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": [],
Expand Down
11 changes: 5 additions & 6 deletions webservice/components/request_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand All @@ -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)
Expand All @@ -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

Expand Down Expand Up @@ -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(
{
Expand All @@ -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

Expand Down
35 changes: 35 additions & 0 deletions webservice/hooks.py
Original file line number Diff line number Diff line change
@@ -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,
)
119 changes: 62 additions & 57 deletions webservice/models/webservice_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)"),
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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`,
Expand All @@ -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)
Expand All @@ -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"):
Expand Down
10 changes: 10 additions & 0 deletions webservice/readme/CONFIGURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
6 changes: 5 additions & 1 deletion webservice/readme/DESCRIPTION.md
Original file line number Diff line number Diff line change
@@ -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.
22 changes: 17 additions & 5 deletions webservice/static/description/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,11 @@ <h1>WebService</h1>
<p><a class="reference external image-reference" href="https://odoo-community.org/page/development-status"><img alt="Production/Stable" src="https://img.shields.io/badge/maturity-Production%2FStable-green.png" /></a> <a class="reference external image-reference" href="http://www.gnu.org/licenses/agpl-3.0-standalone.html"><img alt="License: AGPL-3" src="https://img.shields.io/badge/license-AGPL--3-blue.png" /></a> <a class="reference external image-reference" href="https://github.com/OCA/web-api/tree/19.0/webservice"><img alt="OCA/web-api" src="https://img.shields.io/badge/github-OCA%2Fweb--api-lightgray.png?logo=github" /></a> <a class="reference external image-reference" href="https://translation.odoo-community.org/projects/web-api-19-0/web-api-19-0-webservice"><img alt="Translate me on Weblate" src="https://img.shields.io/badge/weblate-Translate%20me-F47D42.png" /></a> <a class="reference external image-reference" href="https://runboat.odoo-community.org/builds?repo=OCA/web-api&amp;target_branch=19.0"><img alt="Try me on Runboat" src="https://img.shields.io/badge/runboat-Try%20me-875A7B.png" /></a></p>
<p>This module creates WebService frameworks to be used globally.</p>
<p>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.</p>
HTTP call returns the full <tt class="docutils literal">requests.Response</tt> object.</p>
<p>It builds on top of <tt class="docutils literal">webservice_core</tt> (which provides the
<tt class="docutils literal">webservice.backend</tt> model with public/username-password/API key
authentication) to add OAuth2 authentication and <tt class="docutils literal">server_environment</tt>
support.</p>
<p><strong>Table of contents</strong></p>
<div class="contents local topic" id="contents">
<ul class="simple">
Expand Down Expand Up @@ -437,7 +440,16 @@ <h4><a class="toc-backref" href="#toc-entry-3">Example: custom Authorization hea
</pre>
<p>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.</p>
OAuth2 auth header value) are cleared. On upgrade from a version prior
to <tt class="docutils literal">18.0.2.0.1</tt>, a <tt class="docutils literal">webservice.request_content_only</tt> 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 <tt class="docutils literal">requests.Response</tt>
object.</p>
<p>If your code relies on that implicit default, keep the parameter for
now. Once it’s adapted to use the full response object (see <em>Usage</em>),
delete the parameter under <em>Settings &gt; Technical &gt; System Parameters</em> -
new installs never get it set.</p>
</div>
</div>
</div>
Expand Down Expand Up @@ -474,8 +486,8 @@ <h3><a class="toc-backref" href="#toc-entry-8">Maintainers</a></h3>
<p>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.</p>
<p>Current <a class="reference external" href="https://odoo-community.org/page/maintainer-role">maintainer</a>:</p>
<p><a class="reference external image-reference" href="https://github.com/etobella"><img alt="etobella" src="https://github.com/etobella.png?size=40px" /></a></p>
<p>Current <a class="reference external" href="https://odoo-community.org/page/maintainer-role">maintainers</a>:</p>
<p><a class="reference external image-reference" href="https://github.com/etobella"><img alt="etobella" src="https://github.com/etobella.png?size=40px" /></a> <a class="reference external image-reference" href="https://github.com/simahawk"><img alt="simahawk" src="https://github.com/simahawk.png?size=40px" /></a></p>
<p>This module is part of the <a class="reference external" href="https://github.com/OCA/web-api/tree/19.0/webservice">OCA/web-api</a> project on GitHub.</p>
<p>You are welcome to contribute. To learn how please visit <a class="reference external" href="https://odoo-community.org/page/Contribute">https://odoo-community.org/page/Contribute</a>.</p>
</div>
Expand Down
4 changes: 1 addition & 3 deletions webservice/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading