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
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

How to set response status code in controller with type json in odoo17

Suscribirse

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

Se marcó esta pregunta
controllersresponsejsonrpcv17
3 Respuestas
7240 Vistas
Avatar
Muhammad Mudasir
​if not vendor: 
​​response=request.make_json_response(data={'message': 'Invalid ​vendor'},
​headers={"Content-Type": "application/json"},status=401)
​return response

I want to send different status code for different conditions but i get only 200 for every condition 

but the response is like 

{    "jsonrpc": "2.0",    "id": null,    "result": ""} with status 200 

so how to change response status in odoo 17



0
Avatar
Descartar
Avatar
Kothiya Rajesh
Mejor respuesta

Hii Mudasir,

I encountered the same issue with setting the response status code in APIs using type='json'. To solve it, I switched my controller to type='http', which worked perfectly.

While "Cybrosys Techno Solutions Pvt.Ltd" offers a reasonable solution, it only sets the status code inside the result, not for the entire API response. Other approaches also involve some additional customizations.

The solution is simple: you can set the status code and return any response you need by using type='http' and returning request.make_response.


Take a look at the example code below:


@http.route('/api/custom_endpoint', type='http', auth='public', methods=['GET'])
def custom_endpoint(self):
    """
    A simple example of an Odoo GET API endpoint that returns a custom status code.
    :return: JSON response with status code.
    """
    # Example response data
    data = {
        'message': 'Hello, this is a custom response!',
    }
    # Convert the response data to JSON format
    data = json.dumps(data)
    # Create an HTTP response with status code 200 (OK)
    response = request.make_response(
        data,
        headers=[
            ('Content-Type', 'application/json'),
            ('Cache-Control', 'no-cache'),
        ],
        status=200  # You can change this to any status code you need
    )
    return response


0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,

from odoo import http
from odoo.http import request
from werkzeug.wrappers import Response
import json

class YourController(http.Controller):

    @http.route('/your/route', type='json', auth='public', methods=['POST'], csrf=False)
    def your_method(self, **post):
        # Your logic to check vendor
        if not vendor:
            # Create JSON response with status code 401
            response = Response(json.dumps({'message': 'Invalid vendor'}), status=401, content_type='application/json')
            return response
Here we are importing Response from werkzeug.wrappers to get the response status.
It allow creating custom responses as shown!


Hope it helps

0
Avatar
Descartar
Avatar
Nikhil Nakrani
Mejor respuesta

Hi Mudasir,

Can you check this may be help,

https://stackoverflow.com/questions/67646804/how-to-set-response-status-code-in-route-with-type-json-in-odoo-14.

Thanks

0
Avatar
Descartar
Muhammad Mudasir
Autor

Thank you for your response, but this solution does not work for me. I want a solution for Odoo 17. In Odoo 14, there was a class called JsonResponse, but in Odoo 17, this class does not exist.

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

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
How to return/raise a different response than 200 from a controller call?
development controllers v17
Avatar
Avatar
1
mar 24
3678
How to call controller method from Javascript Odoo17 Resuelto
javascript controllers JavascriptCallFromOdoo v17
Avatar
Avatar
Avatar
Avatar
Avatar
4
mar 25
4829
Need want to display username per question who submit it!
username controllers v17 webform
Avatar
0
jul 24
21
How to send json in response at Get Endpoint Odoo v11 Resuelto
json controllers jsonrpc odoov11
Avatar
Avatar
Avatar
2
dic 23
20633
how to change the json response format
api json controllers jsonrpc v15
Avatar
0
nov 22
3316
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • 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 ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren 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