In the ever-changing world of business planning, connecting to Odoo 17 using an API key is essential for making sure different software systems work together smoothly. This blog post is here to guide you step by step, explaining how to prove your identity and get data using simple Python code. The code examples show you how to use a special key to confirm your identity and get information about employees from Odoo.
Odoo comes equipped with support for API keys, and in some cases, using these keys is necessary for carrying out operations through web services. To incorporate API keys into your scripts, all you need to do is substitute your password with the key, keeping the login unchanged. It's crucial to treat the API Key with the same level of care as your password because, essentially, they grant similar access to your user account. Although API keys can't be utilized to log in through the interface, they play a comparable role in accessing your account.
To see the key to your account, simply go to your Preferences (or My Profile) and then open the Account Security tab, you can see this,
By adhering to the steps detailed below, you can create a connection, verify your credentials, and issue API requests to interact with and control data in your Odoo 17 system.
Start by importing two Python modules: requests for managing HTTP requests and JSON for handling JSON data. These modules are vital for engaging with the Odoo API, so ensure they are installed in your Python environment.
import json
import requests
Create a Python function called `get_token` that will serve as the core component for connecting to your Odoo instance. This function handles authentication, header configuration, and API requests.
@http.route('/Token/authenticate', type='http', auth="none",
methods=['POST'], csrf=False, save_session=False, cors="*")
def get_token(self):
byte_string = request.httprequest.data
data = json.loads(byte_string.decode('utf-8'))
username = data['username']
password = data['password']
user_id = request.session.authenticate(request.db, username, password)
if not user_id:
return json.dumps({"error": "Invalid Username or Password."})
env = request.env(user=request.env.user.browse(user_id))
env['res.users.apikeys.description'].check_access_make_key()
token = env['res.users.apikeys']._generate("", username)
payload = {
'user_id': user_id,
'username': username,
'password': password,
'token': token
}
return json.dumps({
"data": payload,
"responsedetail": {
"messages": "UserValidated",
"messagestype": 1,
"responsecode": 200
}
})
In the `get_token` function, set the endpoint URL for your Odoo instance and provide the necessary authentication credentials. It is important to give details about the db in the request body, like the username and password of the db. Then only we can connect with the Odoo.
We can check the response through Postman:
In the “token” parameter, we get the access token if the connection is successful.
Now, we want to authenticate the access token. To authenticate the access token with your Odoo instance, send an authentication request to validate your credentials.
In Odoo, we already have a method to authenticate the access token.
def authenticate_token(self):
IrHttp = request.env['ir.http'].sudo()
IrHttp._auth_method_outlook()
Once you have got the keys on your response, they will appear above the New API Key button.
Now, using this access token, you can connect with other systems and integrate the data securely.
For eg:-
We can Retrieve Employee Data from Odoo using this access token.
@http.route('/api/employee', auth="none", type='http', methods=['GET'],
csrf=False)
def api_get_employee(self, model='res.users', values=None, context=None,
token=None, **kw):
try:
self.authenticate_token()
res = []
env = api.Environment(request.cr, odoo.SUPERUSER_ID,
{'active_test': False})
partners = env[model].search([])
for partner in partners:
partner_vals = {
'name': partner.name,
'login': partner.login,
}
res.append(partner_vals)
return Response(json.dumps(res,
sort_keys=True, indent=4),
content_type='application/json;charset=utf-8',
status=200)
except Exception as e:
return Response(
json.dumps({'error': e.__str__(), 'status_code': 500},
sort_keys=True, indent=4),
content_type='application/json;charset=utf-8', status=200)
Just call the “self.authenticate_token()” this method to authenticate the access token and pass the access token in headers.
Here, you can see the response from the users in Odoo. Like this, you can retrieve any data from Odoo and integrate it with other systems securely.
To read more about connecting to an Odoo 16 using RESTful API, refer to our blog How to Connect to an Odoo 16 Using RESTful API