Enable Dark Mode!
key-elements-of-controller-request-and-response-in-odoo-18.jpg
By: Shafna K

Key Elements of Controller Request & Response in Odoo 18

Technical

In Odoo, controllers are crucial for managing HTTP requests and delivering appropriate responses. They define the routing and functionality for various endpoints, allowing developers to build custom web pages, APIs, and web services. This blog will explore the key elements of controllers, requests, and responses in Odoo 18, providing clear examples to help you understand how they work.
Controllers in Odoo handle HTTP requests from clients (e.g., browsers, mobile apps) and return responses. These requests can be simple webpage requests or more complex API calls. Controllers define routes (URLs) and execute methods based on HTTP methods like GET, POST, PUT, or DELETE.
Here’s a basic example of a controller in Odoo:
from odoo import http
class MyController(http.Controller):
    @http.route('/my_route', auth='public', type='http')
    def my_controller_method(self, **kw):
        return "Hello, this is a response!"
This example defines a route /my_route, and when accessed, it returns the string "Hello, this is a response!".

Types of Requests in Odoo

Odoo primarily deals with two types of requests:
* HTTP Requests (GET, POST)
* JSON Requests (typically for APIs)

a) HTTP Requests

HTTP requests use the common GET and POST methods to send data from the client to the server. For example, a GET request might fetch data from a URL, while a POST request might submit a form.
Example of GET and POST Methods:
class MyController(http.Controller):
    @http.route('/get_example', type='http', auth='public', methods=['GET'])
    def get_method(self, **kw):
        return "This is a GET request!"
    @http.route('/post_example', type='http', auth='public', methods=['POST'])
    def post_method(self, **kw):
        return "This is a POST request!"
In this example, the /get_example route handles a GET request, while /post_example manages a POST request.

b) JSON Requests

JSON Requests allow for API-style communication, sending structured data (usually in JSON format) and receiving structured responses.
Example of a JSON Request:
class MyJsonController(http.Controller):
    @http.route('/json_example', type='json', auth='public')
    def json_method(self, **kw):
        return {"message": "This is a JSON response!"}
When the client sends a request to /json_example, it will receive a JSON response: {"message": "This is a JSON response!"}.

Key Parameters in a Request

Odoo controllers often rely on key parameters passed with each request to handle data and respond accordingly.

a) cr (Database Cursor)

The cr object in Odoo represents the database cursor used to execute SQL queries. It is often used within models but is also available in controller methods for executing queries.

b) context

The context parameter contains additional contextual information, such as user session data, localization settings, and request-specific details. It helps controllers map the request to the correct data or configuration.

c) env

The env object provides access to Odoo models and records within the request. It’s essential for interacting with the database and performing operations like creating, updating, or deleting records.
Example using env to retrieve records:
class MyController(http.Controller):
    @http.route('/customers', auth='user', type='http')
    def get_customers(self, **kw):
        customers = http.request.env['res.partner'].search([])
        return f"Found {len(customers)} customers!"
Here, the env object is used to search for all customer records in the res.partner model.

d) session

The session object manages the user’s session during an HTTP request. It contains authentication details, active transactions, and more.

Security in Requests (CSRF Token)

Odoo provides a method called csrf_token() to generate a Cross-Site Request Forgery (CSRF) token. This token is used to protect against CSRF attacks, ensuring that requests sent to the server are legitimate.
Example of CSRF Protection:
from odoo.http import request
class MyController(http.Controller):
    @http.route('/secure', auth='user', methods=['POST'], csrf=True)
    def secure_route(self, **kw):
        csrf_token = request.csrf_token()
        return f"CSRF token: {csrf_token}"
In this example, a CSRF token is generated and verified during the POST request to /secure.

Handling Responses

In Odoo, you can customize the response returned by a controller using the make_response() function or the Response class.

a) make_response()

This function allows you to generate a custom HTTP response, including headers, cookies, and content.
Example of Custom Response:
from odoo.http import request
class MyController(http.Controller):
    @http.route('/custom_response', auth='public')
    def custom_response(self, **kw):
        response_data = "This is a custom response!"
        headers = {'Content-Type': 'text/plain'}
        return request.make_response(response_data, headers=headers)
In this example, the make_response() function generates a plain text response with custom headers.

b) The Response Class

The Response class provides more control over the HTTP response. It allows you to set content, headers, status codes, cookies, and more.
Example using Response:
from odoo.http import Response
class MyController(http.Controller):
    @http.route('/response_class', auth='public')
    def response_class_method(self, **kw):
        return Response("This is a response using the Response class", status=200)
This method returns a response with a 200 status code.

Error Handling in HTTP Requests

When handling HTTP requests, it's essential to manage errors properly, such as 404 Not Found or 500 Internal Server Error. Odoo provides simple ways to return custom error responses.
Example of Error Handling:
from odoo.http import request, Response
class MyController(http.Controller):
    @http.route('/error_example', auth='public')
    def error_handling(self, **kw):
        try:
            # Attempt to fetch data (this could fail)
            data = http.request.env['some.model'].search([('id', '=', 1)])
            if not data:
                return Response("Resource not found", status=404)
            return f"Found record: {data.name}"
        except Exception as e:
            return Response(f"Internal Server Error: {str(e)}", status=500
In this example, if the record is not found, a 404 Not Found response is returned. If an unexpected error occurs, a 500 Internal Server Error response is sent.

JSON Request with Error Handling

When dealing with JSON requests, it’s important to manage errors appropriately.
Example of JSON Request with Error Handling:
Request:
{
    "jsonrpc": "2.0",
    "method": "call",
    "params": {"context": {}, "arg1": "value1"},
    "id": null
}
Successful Response:
{
    "jsonrpc": "2.0",
    "result": {"res1": "value1"},
    "id": null
}
The Response to the request producing an error will be:
{
    "jsonrpc": "2.0",
    "error": {
        "code": 1,
        "message": "Error occurred",
        "data": {“code”: “codestring”,
                 "debug": "traceback"}
    },
    "id": null
}

Conclusion

Controllers in Odoo 18 are powerful tools for managing requests and crafting custom responses. By understanding how to handle HTTP and JSON requests, utilize key parameters like cr, context, and env, and customize responses with make_response() and the Response class, you can create flexible and secure web services or APIs. With these elements, developers can build rich, interactive web applications directly within the Odoo framework.
To read more about Key Elements of Controller Request & Response in Odoo 17, refer to our blog Key Elements of Controller Request & Response in Odoo 17.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 


whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message