Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Inteligencia artificial
    • IoT
    • VoIP
    • Información
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Sectores
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Asesoría contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos corporativos
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Oficios
    • Servicios de mantenimiento
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de vallas publicitarias
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu asesoría contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Sobre este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Sobre este foro
Ayuda

Create Odoo API Endpoint that can be called when run Odoo wilh Multiple DB

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Esta pregunta ha sido marcada
17.017
4 Respuestas
1081 Vistas
Avatar
tapm2.odoo

HI,

I see that Odoo has an API Endpoint (web/session/authenticate) that can be called even though the request have no sessionID to specify which DB is using.

Every other Endpoint will return 404 if Odoo have multiple active DB.

I create my own endpoint that copy exactly from web/session/authenticate, but it still return 404.

Does anybody know why and how to fix it.

0
Avatar
Descartar
Codesphere Tech

Hello,
You have multiple database in system? check odoo.conf for dbfilter parameter..

tapm2.odoo
Autor

The thing is that the system is required to have multiple active DBs at the same time.

Codesphere Tech

Can you elaborate more about this?

Zehntech Technologies Inc.

Hi,

Thanks for clarifying - this makes the problem much clearer.

You are right, the ?db=mydb parameter alone does not work for anonymous endpoints because Odoo's dispatcher rejects the request with a 404 before it even reads that parameter in a multi-DB setup. The DB selection needs to happen at the dispatcher level, earlier in the request lifecycle.

we have implemented this in a real project.
We built a custom Odoo module for a client who needed anonymous API access across a multi-DB Odoo instance - specifically for a mobile app integration where the calling system had no session context. The setup involved:

A custom ir.http override to intercept the DB name from a request header (X-Odoo-Database) before Odoo's dispatcher rejected the request
All custom endpoints decorated with auth='none' and routed outside the standard session-based flow
A lightweight token validation layer inside the endpoint itself (since there is no Odoo session, you handle your own auth logic)

It worked reliably in production on a 3-DB Odoo 16 instance.

Here is the approach that works for you:
Override _pre_dispatch in ir.http
In your custom module, extend ir.http and override the _pre_dispatch (or _get_default_session depending on your Odoo version) to read the database name from the request early - before routing resolves:

from odoo import models
from odoo.http import request, db_filter

class IrHttp(models.AbstractModel):
_inherit = 'ir.http'

@classmethod
def _pre_dispatch(cls, rule, args):
# Read ?db= param or X-Odoo-Database header early
db = (
request.httprequest.args.get('db')
or request.httprequest.headers.get('X-Odoo-Database')
)
if db and db in db_filter([db]):
request.session.db = db
return super()._pre_dispatch(rule, args)

--------------------------------------------------------------------------------------------------
Then your custom route should be decorated like this:

@http.route('/api/custom/do-something',
type='json',
auth='none', # critical
csrf=False,
save_session=False)
def do_something(self, **kwargs):
...
________________________________________________________________________________________________________
A few important notes:

- The auth='none' is mandatory - auth='public' will still try to resolve a user session which requires a DB context.
- Make sure your endpoint does not touch any ORM or recordset at the point of entry before the DB is set.
- If you are on Odoo 16+, the dispatcher was refactored - let us know your version and we can adjust the override accordingly.

This pattern has been implemented for similar anonymous API gateway scenarios and works reliably in multi-DB setups.
Hope this works for you! Feel free to reach out for further discussion.

Regards,
santosh.sekwadia@zehntech.com

tapm2.odoo
Autor

Thanks a lot for the answer. I get the idea now. I'm using Odoo17 so the dispatcher behaves differently now.

Avatar
Zehntech Technologies Inc.
Mejor respuesta

Hello, 

This behavior is expected in Odoo when running with multiple databases.

The /web/session/authenticate endpoint works without specifying a DB because it is explicitly designed as a public, pre-database selection route. Most other endpoints (including custom ones) require a database context, otherwise Odoo cannot determine which DB to route the request to, resulting in a 404.

Simply copying the controller logic is not enough, as Odoo internally treats such routes differently (e.g., using auth="none" and special dispatch handling).

Possible approaches:

  • Pass the db parameter explicitly in your API request
  • Use a subdomain or routing mechanism to map requests to a specific database
  • Customize the request dispatching (advanced) to handle DB selection before your endpoint is called

Hope this works for you! If you need any help implementing this or want a more optimized approach, feel free to reach out for further discussion

Regards,

Zehntech Technologies Inc.

santosh.sekwadia@zehntech.com

0
Avatar
Descartar
tapm2.odoo
Autor

Hi. Thank you for your answers. I want to make my requirements clearer if it helps.

- I create a custom API Endpoint on Odoo. Ex: /api/custom/do-something
- If my Odoo is having multiple DB: call that API as an anonymous user will return 404.

I think your 3rd approach (Customize the request dispatching (advanced) to handle DB selection before your endpoint is called ) is what I looking for. But i have tried called /api/custom/do-something?db=mydb anonymously, it still returns 404.

Have you guys ever implemented something that can solve or workaround this problem?

Thanks

tapm2.odoo
Autor

Zehntech comment worked for me.

Odoobot
On leave today.
Avatar
Ali Khalid
Mejor respuesta

You're spot on ?db=mydb gets rejected by Odoo's root dispatcher before your /api/custom/do-something even loads in multi-DB setups. Been there!

What works for me:

  • Server-wide module: server_wide_modules = web,base,your_module in odoo.conf. Restart and it matches /web/session/authenticate behavior.

  • Quick ir.http override:

  • python

from odoo import http

class IrHttp(http.Controller):

    @classmethod

    def _authenticate(cls, endpoint, ...):

        db = request.httprequest.args.get('db')

        if db: request.session.db = db

  •         return super()._authenticate(...)

  • Then route: @http.route('/api/custom/<string:db>/do-something', auth='none')

Easy alternative: Just use XML-RPC /xmlrpc/2/db. It handles db params flawlessly.

0
Avatar
Descartar
Avatar
Bloopark systems GmbH & Co. KG, Bloopark systems GmbH & Co. KG
Mejor respuesta
Hi,
First of all, Odoo relies on the existing request session.
You can see it here https://github.com/odoo/odoo/blob/17.0/addons/web/controllers/session.py#L26
It means that Odoo to now that request.session.db already point to the target DB

Second point, in authenticate() route, you can see that it uses explicit db parameter passed by the client
https://github.com/odoo/odoo/blob/17.0/addons/web/controllers/session.py#L30C9-L30C21
and then force creation of DB environment, before passing it to session.info
https://github.com/odoo/odoo/blob/17.0/addons/web/controllers/session.py#L42-L51

It means that in a same session you can not access 2 DB simultaniously
  • using browser, you need to change DB
  • using API, you need to pass specific DB name at session (only that one will allow to access many DB at same time) as for each call you will pass a specific session

Hope it helps

0
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
in POS orderline is it possible to add background color to the discounted product line
17.0
Avatar
Avatar
1
nov 25
1521
Odoo 17 Pos Js development
17.0
Avatar
Avatar
1
ago 25
3843
How can I make the cost field on products readonly? Resuelto
17.0
Avatar
Avatar
Avatar
2
ago 25
2243
Odoo 17 one2many lines issue
17
Avatar
Avatar
Avatar
Avatar
3
jun 25
4637
Change resume view Resuelto
17
Avatar
Avatar
Avatar
Avatar
4
jul 25
2748
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk Slovenščina Español (América Latina) Español Svenska ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones empresariales de código abierto que cubre todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now