HTTP API dispatcher
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.
Table of contents
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 components, 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. 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
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.
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.
Current maintainer:
This module is part of the OCA/rest-framework project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
Metadata
Release files for odoo-addon-http-api-dispatcher 18.0.1.0.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| odoo_addon_http_api_dispatcher-18.0.1.0.0.2-py3-none-any.whl | Python 3 | none | any | Details for odoo_addon_http_api_dispatcher-18.0.1.0.0.2-py3-none-any.whl |
Release files / odoo_addon_http_api_dispatcher-18.0.1.0.0.2-py3-none-any.whl
| Download URL | odoo_addon_http_api_dispatcher-18.0.1.0.0.2-py3-none-any.whl |
|---|---|
| Size | 52.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6e3afba1d4a87fabc7f221f6cdc81b22887aade9ac9503061a3f9020899188c9
|
|
BLAKE2b-256 checksum How to use checksums |
b5b34e92cd3b08e4ea7e73c01aa851623e3d734dc1c2361d24eac1740704ed18
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.4
|
Security for odoo-addon-http-api-dispatcher 18.0.1.0.0.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.