Odoo is a versatile business suite that offers various applications for various business needs. Customizing Odoo to suit specific requirements, such as integrating external systems, can significantly improve workflow efficiency. Creating users via a custom API endpoint is one of the most valuable customisations. This allows you to automate the user creation process, which can be especially valuable in large or integrated systems.
In this post, we’ll walk you through defining an Odoo Via API or custom API endpoint in Odoo that listens for JSON POST requests to create users. The tutorial will cover everything from setting up the endpoint to validating inputs and ensuring secure password handling.
Overview of the Odoo Via API Endpoint
To begin, let’s look at what the custom Odoo via API endpoint will do.
The code snippet defines an HTTP route /api/create_user that listens for JSON POST requests. The endpoint performs several key functions:
JSON Parsing & Validation:
It reads and validates the JSON data.
Field Verification:
It ensures all required fields are provided.
User Duplication Check:
It verifies if the username (login) exists.
Group Assignment:
It assigns a proper user group based on the provided user_type (internal, portal, or public).
User Creation:
It creates the new user record in the res.users model.
Password Encryption:
It securely hashes the password before storing it.
Error Handling:
It catches any exceptions and returns an appropriate error message.
This process allows you to automate user management efficiently, which can be a huge time-saver when integrating external applications.
Step 1: The Code Breakdown
Below is the Python code for a custom Odoo via API controller that creates users via an API call. Let’s dissect it:
1. Route Configuration
class UserAPIController(http.Controller):
@http.route('/api/create_user', type='json', auth='public', methods=['POST'], csrf=False)
@http.route
This decorator defines a new HTTP route. In this case, /api/create_user will listen for incoming requests.
type=’json’
Specifies that the request and response should be in JSON format.
auth=’public’
This means the API endpoint is accessible to the public. In a production environment, ensure proper authentication is applied to protect sensitive data.
methods=[‘POST’]
Only POST requests are accepted, ensuring that data is being sent to the server.
csrf=False
Disables CSRF protection for this route. Be cautious when using this in production; only turn it off if necessary.
2. Data Validation
To create Users in Odoo via API, you need data validation:
def create_user(self):
try:
data = request.httprequest.get_json(silent=True)
username = data.get('username')
password = data.get('password')
email = data.get('email')
phone = data.get('phone')
user_type = data.get('user_type')
if not all([username, password, email, phone, user_type]):
return {'status': 'error', 'message': 'Missing required fields'}
JSON Extraction
Retrieves JSON data from the request.
Field Validation
Ensures that all mandatory fields (username, password, email, phone, user_type) are present; otherwise, it returns an error message.
3. Check Existing Users
Before creating a new user, the endpoint checks if a user with the given or provided username already exists using:
existing_user = request.env['res.users'].sudo().search([('login', '=', username)], limit=1)
if existing_user:
return {'status': 'error', 'message': 'User already exists'}
This ensures that duplicate users are not created, maintaining data integrity.
4. Determining User Group
Based on the user_type provided in the JSON request, the code assigns the new user to the correct group:
if user_type == 'internal':
group_id = request.env.ref('base.group_user').id
elif user_type == 'portal':
group_id = request.env.ref('base.group_portal').id
elif user_type == 'public':
group_id = request.env.ref('base.group_public').id
else:
return {'status': 'error', 'message': 'Invalid user type'}
In Odoo, user permissions are controlled through user groups. We assign the user to the appropriate group based on the user_type provided in the JSON request (either internal, portal, or public). Each group corresponds to a set of permissions in Odoo:
Internal users
(typically employees) are assigned to the group_user group.Portal users
(external customers or partners) are assigned to the group_portal group.Public users
(generic users with limited access) are assigned to the group_public group.
If an invalid user_type is received, the API will return an error message.
6. Creating the User Record
Using Odoo’s ORM, a new user is created with the specified details:
new_user = request.env['res.users'].sudo().create({
'name': username,
'login': username,
'email': email,
'phone': phone,
'groups_id': [(6, 0, [group_id])] if group_id else False
})
After validating the input and ensuring no duplicate exists, the system creates a new user in the res.users model and assigns the appropriate user group.
7. Securing the Password
For security, the user’s password is hashed before being stored:
hashed_password = request.env['res.users']._crypt_context().hash(password)
new_user.sudo()._set_encrypted_password(uid=new_user.id, pw=hashed_password)
return {'status': 'success', 'message': 'User created successfully', 'user_id': new_user.id}
Password Hashing:
The password is hashed using Odoo’s built-in cryptographic context.Updating the User Record:
The hashed password is then set using _set_encrypted_password(), ensuring the plain text password is never stored.
8. Error Handling
The whole function is wrapped in a try-except block. Any unexpected errors are caught, and a user-friendly error message is returned.
Step 2: Testing the API
To test the custom user creation, send a POST request to http://<your-odoo-domain>/api/create_user with the following JSON body:
{
"username" : "Durga",
"password" : "secure123",
"email" : "durga@gmail.com",
"phone" : "9347503061",
"user_type" : "internal"
}
Sample Response
{
"status" : "success",
"message" : "User created successfully",
"user_id" : 42
}
Making User Management Easier with Odoo via API
And that’s how easy it is! You’ve just learned how to create Users in Odoo via API. It’s not just about automating a process; it’s about making your life much easier. Imagine the time saved by not manually creating users every time, especially when you can integrate external systems or apps that automatically push this data into Odoo.
This approach’ll ensure your users are created securely, no duplicates are made, and everything is neatly organised in the right groups. Plus, encrypting passwords before storing them means you’re taking extra care of your data, which is always good!
How do you see this helping your work? Have you tried setting up a similar API, or are you considering implementing this? I’d love to hear about your experiences or challenges with it. Drop a comment below, and let’s talk about how you can make Odoo work even harder for you!



