Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Reports and Integration

Controllers and HTTP Routes

Write Odoo controllers: the http.route decorator, auth modes public user and none, type http versus json, request.env, parameters, CSRF and a runnable routing stand-in.

Besides the backend screens, Odoo serves web pages, downloads and small APIs. All of them are written as controllers: Python classes whose methods are mapped to URLs with the @http.route decorator. The website, the customer portal, payment callbacks and your own endpoints all work this way.

The real HTTP stack cannot run here, so Odoo code is read-only and the stand-ins model routing and request handling in plain Python.

A first controller

Python
from odoo import http
from odoo.http import request


class LibraryController(http.Controller):

    @http.route("/library/books", type="http", auth="public", website=True)
    def book_list(self, **kwargs):
        books = request.env["library.book"].sudo().search([("state", "=", "available")])
        return request.render("library.book_list_page", {"books": books})

    @http.route("/library/book/<int:book_id>", type="http", auth="public", website=True)
    def book_detail(self, book_id, **kwargs):
        book = request.env["library.book"].browse(book_id).exists()
        if not book:
            return request.not_found()
        return request.render("library.book_detail_page", {"book": book})

The controller class lives in a controllers/ package, imported from the module's __init__.py. The file controllers/__init__.py imports each controller file; forgetting that import is the classic reason a route returns 404.

The route decorator

@http.route(route, type, auth, methods, website, csrf, ...):

  • route: one URL or a list. Use converters such as <int:id>, <string:slug> or <model("library.book"):book>, which loads the record for you.
  • type: "http" for pages and downloads, "jsonrpc" (named "json" in older versions; check your version) for JSON requests that carry a JSON-RPC body.
  • auth: who may call it.
    • "user": a logged-in user; others get redirected to the login page.
    • "public": anyone; a logged-out visitor runs as the website's public user.
    • "none": no database even selected. Used for very early routes such as database selection.
  • methods: for example ["POST"].
  • website=True: wraps the page in the website layout and enables features such as multi-website and translations.
  • csrf: protects POST routes of type http. Keep it enabled. A form needs <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>.

Parameters and responses

A URL parameter or a query/form field is passed as a keyword argument: /library/search?q=dune calls search(self, q=None, **kwargs). A type="http" method returns a string, a rendered template (request.render) or a Response, plus helpers like request.redirect("/library/books"). A type="jsonrpc" method returns a value that Odoo wraps into a JSON-RPC result, and raised errors are wrapped as JSON-RPC errors.

Python
    @http.route("/library/api/available", type="jsonrpc", auth="user")
    def available(self, limit=10):
        books = request.env["library.book"].search([("state", "=", "available")], limit=limit)
        return books.read(["name", "isbn"])

Because auth="user" was used, the search runs as that user and respects their access rights and record rules (Record Rules). Public routes run as the public user, which usually has almost no rights. That is why public code often uses .sudo(). Keep that sudo small, check tokens or ownership first, and select exact fields (Field Security, sudo and Safe Coding).

flowchart TD
    A["HTTP request"] --> B["Route match<br/>(werkzeug map)"]
    B --> C{"auth mode"}
    C -- user --> D["Session needed;<br/>run as that user"]
    C -- public --> E["Run as public user"]
    C -- none --> F["No registry"]
    D --> G["Controller method"]
    E --> G
    F --> G
    G --> H["Response"]

Odoo finds the route, resolves who the request runs as, and then calls your method.

Inheriting a controller

To change an existing route, subclass the controller and override the method, calling super(). Odoo re-registers the route with your class. This is the mechanism behind many "customise checkout" modules, so you must keep the same decorator arguments when you override.

Routing stand-in

Odoo uses werkzeug to match routes. Pyodide does not guarantee werkzeug here, so this stand-in writes a tiny matcher with regular expressions, including a typed converter and an auth check.

Python A tiny router with converters and auth

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A JSON endpoint stand-in

JSON-RPC wraps both success and failure in an envelope. This stand-in builds the envelope a type="jsonrpc" route returns, and shows how Odoo reports exceptions to the caller.

Python Wrap results in a JSON-RPC envelope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Safety checklist

  • Prefer auth="user" unless the page must be public.
  • Keep csrf on for state-changing POST routes. Disabling it is only reasonable for third-party webhooks that you verify another way (a signature, for example payment providers).
  • Never trust IDs from the URL. Use .exists(), check ownership, or require an access token (the portal mixin's access_token pattern).
  • Validate input types; query parameters arrive as strings.
  • Do not return stack traces or internal data in custom responses.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does auth="public" mean on a route?

    Public routes are open to logged-out visitors, who run as the website's public user.
  2. 2. A new controller file exists but its routes return 404. What is the most likely cause?

    Python files are only loaded when imported, so the controller must be imported by the package.
  3. 3. Which route converter loads a record from the URL?

    The model converter looks up the record by ID and passes the browse record to the method.
  4. 4. Why is csrf=False normally a bad idea on an http POST route?

    CSRF protection checks a token that other sites cannot know, so disabling it opens the route to cross-site request forgery.

Summary

  • Controllers are classes with @http.route methods; import them from the package __init__.
  • type selects page versus JSON-RPC; auth selects who the request runs as.
  • Public routes need extra care: check ownership or tokens before using sudo().
  • Keep CSRF protection on and validate all input.
  • Override a route by subclassing the controller and calling super().

Next: External API with XML-RPC and JSON-RPC