Connect With Odoo 17 Using API Key
When it comes to the ever-changing world of business planning, connecting to Odoo 17 using an API key is essential to guaranteeing smooth software platform integration. This blog post will demonstrate how to collect data and authenticate yourself using simple Python scripts. The code samples show you how to use a unique key to authenticate yourself and retrieve employee information for Odoo.
Odoo has support for API keys; in certain situations, using these keys is required to perform actions via web services. All you have to do to include API keys in your scripts is replace your password with the key while maintaining the login. Since your password and the API Key essentially provide the same access to your user account, it’s important to handle both carefully. While API keys are not used for logging in via the interface, they are as important for gaining access to your account.
To see the key for your account, just choose Preferences and click the Account Security tab.
You can connect to your Odoo 17 and submit API to manipulate and access data by following the steps.
To begin, import requests and JSON for handling HTTP requests and JSON data, respectively.
import requests
JSON import
Make get_token, for a Python function, which will be the main part of connecting to your Odoo. This method manages 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 method, set the endpoint URL for your Odoo and provide the necessary login details. The request body must contain database information, such as the username and password. Then, only we may access the Odoo.
We may use Postman to verify the response:
def authenticate_token(self):
IrHttp = request.env['ir.http'].sudo()
IrHttp._auth_method_outlook()
After the keys are in your answer, they will show up above the button for a new API key.
You can now securely integrate the data and connect to other systems using this access token.
For instance:
We can use this access token to retrieve employee data from Odoo.
@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)
To authenticate the access token and pass it in headers, simply call the “self.authenticate_token()” method.
This is where you may view the Odoo user reaction. In this way, you may safely integrate any data from Odoo with other systems and access it.
"Unlock the Full Potential of Your Business with Odoo ERP!"
"Get a Cost Estimate for Your ERP Project, Absolutely FREE!"
Get a Free Quote