Skip to content

Mastering the Odoo Mobile App Controller: Seamless API Integration for Dynamic Applications

odoo mobile app controller 7 highest total score and the most relevant keyphrase

Are you looking to build a powerful mobile application that eamlessly integrates with your Odoo system? The thought of navigating complex Odoo web services can be daunting for many developers, especially those new to Odoo’s ecosystem. However, there’s a more streamlined and developer-friendly approach: leveraging the Odoo Mobile App Controller. This guide will show you how to utilize Odoo controllers to simplify communication, enabling your mobile app to authenticate, fetch data, and create records with remarkable ease.

This tutorial is inspired by a comprehensive video demonstration. You can watch the original explanation here: Odoo Mobile App Development – Authentication, Fetching Data & Creating Records Using Controller.

Why Choose the Odoo Mobile App Controller for Your Integration?

Integrating a mobile application with Odoo often conjures images of intricate API documentation and steep learning curves. While Odoo does offer robust web services, they can sometimes be overly complex for standard mobile app interactions. This is where the Odoo Mobile App Controller shines. By creating custom controllers, Odoo developers can tailor specific endpoints that expose only the necessary data and functionalities, making it incredibly simple for mobile developers to consume.

This approach offers several compelling advantages:

  • Simplicity: No need to delve into the full breadth of Odoo’s RPC (Remote Procedure Call) XML-RPC or JSON-RPC. Mobile developers can use standard HTTP POST/GET requests with JSON payloads.
  • Customization: You have complete control over what data is exposed and how it’s structured, optimizing responses for mobile performance.
  • Security: Implement fine-grained access control using Odoo’s built-in authorization mechanisms on a per-controller basis.
  • Efficiency: Reduce overhead by sending and receiving only the data your mobile app requires, leading to faster response times and a better user experience.
  • Maintainability: Custom controllers are part of your Odoo module, making them easier to manage, version control, and deploy alongside your Odoo customizations.

Ready to unlock a more efficient way to connect your mobile app with Odoo? Let’s dive into the practical steps.

Prerequisites for Odoo Mobile App Controller Development

Before we begin, ensure you have the following set up:

  • Odoo 12 or higher instance: The concepts apply broadly, but the examples are based on Odoo 12.
  • Basic understanding of Odoo development: Familiarity with Odoo models, modules, and Python is beneficial.
  • Postman (or a similar API testing tool): Essential for testing your API endpoints before integrating them into a mobile app. You can download Postman from their official website.
  • An Odoo custom module: We’ll be adding our controllers to a custom module (e.g., om_hospital or odoo_development_tutorials). If you don’t have one, create a basic module.
  • Python development environment: Such as PyCharm, for writing your Odoo controller code.

With these in place, let’s start with the fundamental step: authentication.

I. Authenticating Your Mobile App with the Odoo Mobile App Controller

Authentication is the cornerstone of any secure integration. It ensures that only authorized users can interact with your Odoo database. Odoo provides a standard controller for this purpose, which we can leverage directly.

Step 1: Identify the Odoo Authentication Controller

Odoo has a built-in HTTP route designed for session-based authentication:
/web/session/authenticate

This endpoint accepts a POST request with user credentials and returns a session ID upon successful authentication.

Step 2: Craft Your Authentication Request

We’ll use Postman to simulate a request from your mobile app.

  1. Open Postman: Launch the Postman application.
  2. Create a New Request: Click the + button to create a new request.
  3. Set Request Type to POST: In the dropdown menu next to the URL field, select POST.
  4. Enter the URL: Construct the URL for your Odoo instance followed by the authentication route.
    • Example: http://localhost:8012/web/session/authenticate (Replace localhost:8012 with your Odoo server’s IP address and port).
  5. Configure the Request Body:

    • Go to the Body tab.
    • Select raw and then choose JSON from the dropdown menu.
    • Enter the following JSON payload, replacing the placeholder values with your Odoo database name, login (email/username), and password:
    {
      "jsonrpc": "2.0",
      "params": {
        "db": "your_database_name",
        "login": "your_username_or_email",
        "password": "your_password"
      }
    }
    
    • For instance, if your database is dev12, login is admin, and password is admin, it would look like:
      {
      "jsonrpc": "2.0",
      "params": {
      "db": "dev12",
      "login": "admin",
      "password": "admin"
      }
      }
      

Step 3: Send the Request and Process the Response

  1. Click Send: Postman will send the request to your Odoo instance.
  2. Analyze the Response:

    • Successful Authentication: You will receive a JSON response containing result, including details like server_version, session_id, uid, username, and other user-related information. The session_id is critical – copy it, as you’ll need it for all subsequent authenticated requests to your custom Odoo Mobile App Controller endpoints.

      {
        "jsonrpc": "2.0",
        "result": {
          "server_version": "12.0",
          "session_id": "YOUR_UNIQUE_SESSION_ID_HERE",
          "uid": 2,
          "username": "admin",
          "partner_id": 3,
          "company_id": 1
          // ... more details
        }
      }
      
    • Failed Authentication: If you provide incorrect credentials, the response will indicate an error, typically "Access denied". Double-check your database name, login, and password.

With a valid session_id in hand, your mobile app is now authenticated and ready to interact with your Odoo data.

II. Fetching Data from Odoo Using a Custom Odoo Mobile App Controller

Once authenticated, your mobile app will likely need to retrieve data from Odoo. This is where custom controllers become incredibly powerful, allowing you to expose specific data sets tailored for your mobile interface.

Step 1: Create a Custom Odoo Mobile App Controller for Data Retrieval

Let’s create a controller that fetches patient records from a hospital.patient model.

  1. Navigate to your custom module: Locate your module’s controllers directory (e.g., om_hospital/controllers/).
  2. Open/Create main.py: Add or modify the main.py file within this directory.
  3. Add the Controller Code:

    from odoo import http
    from odoo.http import request
    
    class HospitalMobileController(http.Controller):
        @http.route('/get_patients', type='json', auth='user', methods=['GET'])
        def get_patients(self):
            """
            Odoo Mobile App Controller: Fetches patient data from the hospital.patient model.
            Requires authentication (auth='user').
            """
            patients_list = []
            try:
                # Search for all patient records
                # For a real app, you might add filters, pagination, or search queries
                patient_records = request.env['hospital.patient'].sudo().search([])
    
                for patient in patient_records:
                    vals = {
                        'id': patient.id,
                        'name': patient.patient_name,
                        'sequence': patient.name_sequence,
                        'email': patient.email_id, # Assuming an email_id field
                        # Add any other fields relevant for your mobile app
                    }
                    patients_list.append(vals)
    
                return {
                    'status': 'success',
                    'message': 'Successfully retrieved all patient records via Odoo Mobile App Controller.',
                    'patients': patients_list
                }
            except Exception as e:
                return {
                    'status': 'error',
                    'message': f'Failed to fetch patients: {str(e)}',
                    'patients': []
                }
    
    • Explanation:
      • @http.route('/get_patients', type='json', auth='user', methods=['GET']): This decorator defines our custom Odoo Mobile App Controller endpoint.
        • /get_patients: The URL path for this endpoint.
        • type='json': Specifies that the request and response bodies will be in JSON format.
        • auth='user': Crucially, this ensures that only authenticated Odoo users can access this route. The session_id from the authentication step validates the user.
        • methods=['GET']: Indicates that this controller expects a GET request.
      • request.env['hospital.patient'].sudo().search([]): This line fetches all records from the hospital.patient model. .sudo() is used here for simplicity in a tutorial context to bypass access rights, but in a production environment, you should carefully manage user permissions and remove .sudo() if the calling user has sufficient rights, or apply it selectively.
      • The code iterates through patient_records, creating a dictionary for each patient containing id, name, sequence, and email. You can extend this vals dictionary to include any other fields your mobile app needs.
      • The function returns a JSON dictionary with a status, message, and the patients_list. We’ve also added basic error handling.

Step 2: Update Your Module’s __init__.py

Ensure your controller file is imported. In your module’s __init__.py file (e.g., om_hospital/__init__.py), add:

from . import controllers

Step 3: Restart Odoo Service

After any code changes in Odoo, you must restart your Odoo service for the changes to take effect.

Step 4: Test Your Data Fetching Odoo Mobile App Controller

Back in Postman, let’s test this new endpoint.

  1. Create a New Request: New tab in Postman.
  2. Set Request Type to GET: Select GET.
  3. Enter the URL: http://localhost:8012/get_patients (Adjust as per your Odoo instance).
  4. Configure Headers: This is vital for authenticated requests.
    • Go to the Headers tab.
    • Add a new header:
      • Key: X-Openerp-Session-Id
      • Value: Paste the session_id you obtained from the authentication step.
  5. Leave Body Empty: For a GET request, the body is typically empty.
  6. Click Send:

  7. Analyze the Response:

    • You should receive a JSON array of patient records, each with the id, name, sequence, and email as defined in your controller. If you added a new patient (e.g., “Alan”) in Odoo’s UI, it should appear in this list.
    {
      "status": "success",
      "message": "Successfully retrieved all patient records via Odoo Mobile App Controller.",
      "patients": [
        {
          "id": 7,
          "name": "Automates",
          "sequence": "HP004",
          "email": "automate@example.com"
        },
        {
          "id": 8,
          "name": "James",
          "sequence": "HP003",
          "email": "james@example.com"
        },
        // ... more patient records, including "Alan"
      ]
    }
    

This confirms your mobile app can now securely fetch data from Odoo using your custom Odoo Mobile App Controller.

III. Creating Records in Odoo Using a Custom Odoo Mobile App Controller

Beyond reading data, mobile applications often need to create new records in Odoo. This process is equally straightforward with a dedicated Odoo Mobile App Controller.

Step 1: Create a Custom Odoo Mobile App Controller for Record Creation

We’ll add another method to our HospitalMobileController to handle patient creation.

  1. Open om_hospital/controllers/main.py:
  2. Add the Controller Code:

    from odoo import http
    from odoo.http import request
    
    class HospitalMobileController(http.Controller):
        # ... (get_patients method from above) ...
    
        @http.route('/create_patient', type='json', auth='user', methods=['POST'])
        def create_patient(self):
            """
            Odoo Mobile App Controller: Creates a new patient record.
            Expects 'name' and optionally 'email_id' in the JSON request body.
            Requires authentication (auth='user').
            """
            data = request.get_json_request() # Gets the JSON body from the request
            vals = {}
            new_patient_id = False
    
            if not data:
                return {
                    'status': 'error',
                    'message': 'No data provided in the request body.'
                }
    
            try:
                if 'name' in data and data['name']:
                    vals['patient_name'] = data['name']
                else:
                    return {
                        'status': 'error',
                        'message': 'Patient name is required.'
                    }
    
                if 'email_id' in data and data['email_id']:
                    vals['email_id'] = data['email_id']
                # You can add more fields here as needed
                # Example: if 'age' in data: vals['patient_age'] = data['age']
    
                # Create the patient record
                new_patient = request.env['hospital.patient'].sudo().create(vals)
                new_patient_id = new_patient.id
    
                return {
                    'status': 'success',
                    'message': f'Patient created successfully via Odoo Mobile App Controller. ID: {new_patient_id}',
                    'id': new_patient_id
                }
            except Exception as e:
                return {
                    'status': 'error',
                    'message': f'Failed to create patient: {str(e)}',
                    'id': new_patient_id
                }
    
    • Explanation:
      • @http.route('/create_patient', type='json', auth='user', methods=['POST']): Defines the new endpoint for creating patients. It accepts POST requests and requires authentication.
      • data = request.get_json_request(): This crucial line parses the incoming JSON payload from the mobile app.
      • vals = {}: An empty dictionary vals is initialized to hold the data for the new patient.
      • if 'name' in data and data['name']:: We extract the name from the incoming JSON. Remember, patient_name must be the actual technical field name in your hospital.patient model. We’ve also added basic validation for the name.
      • if 'email_id' in data and data['email_id']:: Similarly, we extract email_id.
      • request.env['hospital.patient'].sudo().create(vals): This command creates a new record in the hospital.patient model using the vals dictionary. Again, .sudo() is used for simplicity; in production, manage access rights carefully.
      • The function returns a JSON response indicating success or failure, along with the id of the newly created patient.

Step 2: Restart Odoo Service

Remember to restart your Odoo service after adding this new controller method.

Step 3: Test Your Record Creation Odoo Mobile App Controller

Use Postman to simulate creating a new patient from your mobile app.

  1. Create a New Request: Open a new tab in Postman.
  2. Set Request Type to POST: Select POST.
  3. Enter the URL: http://localhost:8012/create_patient (Adjust as per your Odoo instance).
  4. Configure Headers:
    • Go to the Headers tab.
    • Add: Key: X-Openerp-Session-Id, Value: Your session_id.
  5. Configure the Request Body:

    • Go to the Body tab.
    • Select raw and then choose JSON.
    • Enter the JSON payload with the patient’s details:
    {
      "name": "Subscribe the Channel",
      "email_id": "subscribe@example.com"
    }
    
    • Important: Ensure the keys ("name", "email_id") exactly match the expected keys in your Odoo Mobile App Controller (data['name'], data['email_id']) and correspond to your Odoo model’s technical field names.
  6. Click Send:

  7. Analyze the Response:

    • You should receive a JSON response indicating success and the id of the newly created patient.
    {
      "status": "success",
      "message": "Patient created successfully via Odoo Mobile App Controller. ID: 12",
      "id": 12
    }
    
    • Verify in Odoo: Log into your Odoo instance, navigate to the Patients section, and confirm that the new patient record (“Subscribe the Channel” with the provided email) has been created.

Congratulations! Your mobile app can now perform full CRUD (Create, Read, Update, Delete – though we only covered Create and Read here) operations with your Odoo database, all powered by simple and robust Odoo Mobile App Controller endpoints.

Advanced Considerations for Your Odoo Mobile App Controller

While the basic setup is complete, building a production-ready mobile app integration requires attention to several advanced aspects.

1. Security Best Practices

  • Input Validation: Always validate data received from the mobile app to prevent malicious injections or incorrect data types. This is crucial for the integrity of your Odoo database.
  • Authorization: The auth='user' attribute on your controller routes is a good start, but consider more granular access control. You might check specific user groups or record rules within your controller methods. Avoid .sudo() in production unless absolutely necessary and thoroughly justified.
  • HTTPS: Always use HTTPS for all communication between your mobile app and Odoo to encrypt data in transit, protecting sensitive information like credentials and patient data.
  • API Keys/Tokens: For enhanced security, consider implementing an API key system or more advanced token-based authentication (like OAuth2) in addition to session IDs for certain endpoints, especially if external services or multiple applications are interacting with Odoo.

2. Error Handling and User Feedback

Robust error handling is paramount. Your Odoo Mobile App Controller should:

  • Catch Exceptions: Use try...except blocks to gracefully handle potential errors (e.g., database constraints, incorrect data).
  • Return Informative Error Messages: Provide clear, concise error messages in the JSON response so the mobile app can understand what went wrong and present appropriate feedback to the user.
  • Standardize Error Codes: Adopt a consistent system for error codes to make debugging and client-side error handling easier.

3. Performance Optimization

Mobile apps demand fast responses. Optimize your Odoo Mobile App Controller endpoints by:

  • Limiting Data Fetched: Only retrieve the fields and records absolutely necessary for the mobile app’s current view. Avoid search([]) for large datasets without limit and offset.
  • Pagination: Implement pagination for fetching large lists of records (e.g., search([], offset=0, limit=20)). This prevents overwhelming the mobile device and improves load times.
  • Caching: Explore caching mechanisms on the mobile app side to reduce redundant requests to Odoo.
  • Database Queries: Optimize your Odoo model methods or controller logic to ensure efficient database queries.

4. Choosing the Right Fields

When fetching data, be selective. If your hospital.patient model has 50 fields, but your mobile app only needs 5, only include those 5 in your vals dictionary within the controller. This reduces JSON payload size and network bandwidth usage.

5. Model Field Names: A Crucial Detail

One of the most common pitfalls in Odoo integrations is using incorrect field names. Odoo uses “technical names” for its fields. To ensure you’re using the correct name:

  • Activate Developer Mode: In your Odoo UI, enable developer mode (often found at the bottom right of the screen or in your settings).
  • Inspect Field: Go to the form view of your model (e.g., a patient record), hover over the field you’re interested in, and a tooltip will show its “Technical Name.” Use this exact name in your controller code (patient.patient_name, data['email_id']).

You can also use your Odoo Mobile App Controller to provide links or IDs to related records. For example, when fetching a patient, you might include the ID of their assigned doctor, allowing the mobile app to then fetch doctor details via another controller endpoint. For more on Odoo controllers, you can refer to the official Odoo documentation on HTTP Controllers.

Conclusion: Empower Your Mobile App with Odoo Mobile App Controllers

The Odoo Mobile App Controller provides an incredibly flexible and robust way to build dynamic mobile applications that integrate seamlessly with your Odoo system. By creating custom API endpoints, you simplify the development process for mobile engineers, enhance security, and optimize performance.

Whether you’re building an internal tool for field agents, a customer portal, or a specialized healthcare application, mastering the Odoo Mobile App Controller will empower you to unlock the full potential of your Odoo data on mobile devices. Start experimenting with these techniques today, and you’ll soon discover the ease and power of a well-integrated Odoo mobile solution.

If you have any questions or need further assistance with your Odoo mobile app development, don’t hesitate to reach out! Feel free to leave a comment below or connect with us on social media.


Discover more from teguhteja.id

Subscribe to get the latest posts sent to your email.

Leave a Reply

WP Twitter Auto Publish Powered By : XYZScripts.com