Metadata-Version: 2.1
Name: odoo-addon-http_api_dispatcher
Version: 18.0.1.0.0.4
Requires-Python: >=3.10
Requires-Dist: odoo==18.0.*
Summary: Generic dispatcher for JSON APIs: parsing, validation, errors.
Home-page: https://github.com/OCA/rest-framework
License: LGPL-3
Author: Camptocamp,Odoo Community Association (OCA)
Author-email: support@odoo-community.org
Classifier: Programming Language :: Python
Classifier: Framework :: Odoo
Classifier: Framework :: Odoo :: 18.0
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
Classifier: Development Status :: 3 - Alpha
Description-Content-Type: text/x-rst

.. image:: https://odoo-community.org/readme-banner-image
   :target: https://odoo-community.org/get-involved?utm_source=readme
   :alt: Odoo Community Association

===================
HTTP API dispatcher
===================

.. 
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   !! This file is generated by oca-gen-addon-readme !!
   !! changes will be overwritten.                   !!
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   !! source digest: sha256:a03da32899e457057ffdd8493cb6a35d38c921b8353a014c12f24ec4f9983bf8
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

.. |badge1| image:: https://img.shields.io/badge/maturity-Alpha-red.png
    :target: https://odoo-community.org/page/development-status
    :alt: Alpha
.. |badge2| image:: https://img.shields.io/badge/license-LGPL--3-blue.png
    :target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html
    :alt: License: LGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Frest--framework-lightgray.png?logo=github
    :target: https://github.com/OCA/rest-framework/tree/18.0/http_api_dispatcher
    :alt: OCA/rest-framework
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
    :target: https://translation.odoo-community.org/projects/rest-framework-18-0/rest-framework-18-0-http_api_dispatcher
    :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/rest-framework&target_branch=18.0
    :alt: Try me on Runboat

|badge1| |badge2| |badge3| |badge4| |badge5|

Technical module providing a generic dispatcher for JSON APIs: routes of
type ``http_api``.

It takes care of the plumbing common to any API endpoint:

- parse params from the query string and the body (JSON, forms) once
- set the language from the ``Accept-Language`` header
- validate and convert input params and results via pluggable params
  declared on the route (see ``http_api_cerberus`` for Cerberus schemas)
- serialize results as JSON (dates as ISO strings, decimals as floats)
- turn exceptions into JSON error responses with proper status codes
- provide hooks to extend each step via standard Odoo inheritance

To declare endpoints on classes that are not controllers (eg: services)
whose routes are generated, see ``endpoint_spec``.

The error format and the main behaviors are compatible with
``base_rest`` to ease the migration of existing APIs.

.. IMPORTANT::
   This is an alpha version, the data model and design can change at any time without warning.
   Only for development or testing purpose, do not use in production.
   `More details on development status <https://odoo-community.org/page/development-status>`_

**Table of contents**

.. contents::
   :local:

Use Cases / Context
===================

``base_rest`` (OCA/rest-framework) has been the foundation of many APIs,
including the Shopfloor apps. Over time it showed some limits:

- it is a monolith: dispatcher, service layer, validation, documentation
  and routing are bound together and you cannot use one piece without
  the others
- services must be ``component``\ s, a second registry with its own
  inheritance and boot lifecycle, which is often used only to look up a
  class by name
- controllers are generated at boot from the services, making routing
  hard to follow and to customize

The ``fastapi`` stack is a way to go for new standalone APIs, but moving
existing APIs to it means rewriting every service and schema and
endpoints are not extendable models. Plus, it pulls in more external
dependencies that for many cases are not needed.

This module is the base of a lighter stack, made of small modules that
can be used separately and extended via standard Odoo inheritance:

- ``http_api_dispatcher``: the ``http_api`` route type (parsing,
  validation hooks, JSON errors) usable by plain Odoo controllers
- ``endpoint_spec``: declare endpoints on services, for routes
  generators
- ``http_api_cerberus``: Cerberus validation
- ``openapi_doc_base``: API docs from the actual routes
- ``endpoint_route_handler`` generators: routes computed from the code
  without storing a row per route

Goals:

- simplify the ``base_rest`` stack without moving to ``fastapi``
- keep modules small and reusable
- drop the dependency on ``component``, staying highly customizable
  (routing keys per route, ``ir.http`` hooks per database)
- stay compatible with ``base_rest`` clients (error format, validation
  behavior) to allow a gradual migration

Configuration
=============

To include the traceback and the description of any error in the
responses, set ``dev_mode`` in the ``http_api`` section of the
configuration file:

::

   [http_api]
   dev_mode = True

The ``dev_mode`` key of the ``base_rest`` section is honored as well.
Never enable it in production.

Usage
=====

Controllers
-----------

Use the ``http_api`` type on standard routes. Extra routing keys drive
the behavior of the dispatcher:

::

   from odoo import http
   from odoo.addons.http_api_cerberus.params import CerberusParam

   class PartnerAPI(http.Controller):

       @http.route(
           "/api/partner/<int:id>",
           type="http_api",
           auth="user",
           methods=["GET"],
           output=CerberusParam({"id": {"type": "integer"}, "name": {"type": "string"}}),
       )
       def get(self, id):
           partner = http.request.env["res.partner"].browse(id)
           return {"id": partner.id, "name": partner.name}

Any value returned by the endpoint is serialized as JSON, unless it's
already a response (eg: ``request.make_response``).

Routing keys:

+------------------+----------------------------------------------------------------------+
| Key              | Meaning                                                              |
+==================+======================================================================+
| ``input``        | ``ApiParam`` validating and converting request params                |
+------------------+----------------------------------------------------------------------+
| ``input_kwarg``  | keyword used to pass non-dict input values (default ``payload``)     |
+------------------+----------------------------------------------------------------------+
| ``output``       | ``ApiParam`` validating and converting the result                    |
+------------------+----------------------------------------------------------------------+
| ``prepare``      | callable or list of callables receiving the ``ApiCall``, run before  |
|                  | input validation (eg: check headers, update the context)             |
+------------------+----------------------------------------------------------------------+
| ``body_parsers`` | ``{mimetype: callable}`` overriding body parsers                     |
+------------------+----------------------------------------------------------------------+
| ``query_parser`` | callable overriding the query string parser                          |
+------------------+----------------------------------------------------------------------+
| ``error_map``    | ``[(exception classes, HTTP exception class, include description)]`` |
|                  | evaluated before the default error mapping                           |
+------------------+----------------------------------------------------------------------+
| ``json_encoder`` | ``json.JSONEncoder`` subclass for the response                       |
+------------------+----------------------------------------------------------------------+
| ``csrf``         | as for any Odoo route (default ``True``). The token is read from the |
|                  | ``X-CSRF-Token`` header, else from the ``csrf_token`` param of the   |
|                  | query or the body. Set it to ``False`` for token based APIs          |
+------------------+----------------------------------------------------------------------+

Params from the URL (eg: ``<int:id>``) always win over query and body
params. The query string and the body are parsed on first access. An
``input`` param reading only the query or the body keeps the other one
unparsed.

Params
------

Subclass ``odoo.addons.http_api_dispatcher.params.ApiParam`` and
implement ``from_params``, ``to_response`` and optionally
``to_json_schema`` (used to generate API docs). Raise
``odoo.addons.http_api_dispatcher.errors.ApiValidationError`` for
invalid input: the details of the errors are returned in the ``errors``
key of the response.

Errors
------

================================== ============ ===================
Exception                          Status       Description in body
================================== ============ ===================
``SessionExpiredException``        401          no
``MissingError``                   404          no
``AccessError``, ``AccessDenied``  403          no
``UserError``, ``ValidationError`` 400          yes
werkzeug ``HTTPException``         its own code yes for 4xx
anything else                      500          no
================================== ============ ===================

The body looks like
``{"code": 400, "name": "Bad Request", "description": "..."}`` plus the
content of the ``rest_json_info`` attribute of the exception, if any.

Hooks
-----

Each step of the pipeline is a classmethod of ``ir.http`` that can be
extended:

- ``_http_api_prepare(call)``
- ``_http_api_validate_input(call)``
- ``_http_api_call(call)``: wrap it to log or profile calls
- ``_http_api_validate_output(call)``
- ``_http_api_make_response(call)``

All of them receive an ``ApiCall`` holding the request, the endpoint,
the result and an ``extra`` dict for your own data. The params are
exposed lazily: ``call.query``, ``call.body`` and ``call.params`` (the
merged dict, built on first access).

Known issues / Roadmap
======================

- Parse lists from the query string based on the input schema (repeated
  keys) instead of keeping only the last value.
- Generic call logging module hooking ``_http_api_call`` (split of
  ``rest_log`` from ``base_rest``).

Bug Tracker
===========

Bugs are tracked on `GitHub Issues <https://github.com/OCA/rest-framework/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 <https://github.com/OCA/rest-framework/issues/new?body=module:%20http_api_dispatcher%0Aversion:%2018.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.

Do not contact contributors directly about support or help with technical issues.

Credits
=======

Authors
-------

* Camptocamp

Contributors
------------

- Simone Orsi <simone.orsi@camptocamp.com>

Other credits
-------------

Error handling and request parsing are derived from ``base_rest``
(OCA/rest-framework) by ACSONE SA/NV.

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 <https://odoo-community.org/page/maintainer-role>`__:

|maintainer-simahawk| 

This module is part of the `OCA/rest-framework <https://github.com/OCA/rest-framework/tree/18.0/http_api_dispatcher>`_ project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
