REST API/OpenAPI/Swagger
by IT-Projects LLC https://t.me/sync_studio , Ivan Yelizariev https://t.me/sync_studioLines of code | 2122 |
Technical Name |
openapi |
License | LGPL-3 |
Website | https://t.me/sync_studio |
Also available in version | v 8.0 v 14.0 v 13.0 v 15.0 v 10.0 v 11.0 v 16.0 |
REST API/OpenAPI/Swagger
Secure tool for convenient integrations
Version: v12.0.1.1.11
Tested and maintained by
IT Projects Labs
Assitance: help@itpp.dev
- Grant exact access rights needed for an integration
- Load generated OpenAPI Specification into Postman, Swagger Editor or any other tools that supports it
- Monitor API requests/responses at desired level of details
Easy to use in any programming languages
# https://github.com/Yelp/bravado from bravado.requests_client import RequestsClient from bravado.client import SwaggerClient http_client = RequestsClient() http_client.set_basic_auth('yourdomain.example.com', 'DATABASE-NAME', 'USER-TOKEN') odoo = SwaggerClient.from_url( 'https://yourdomain.example.com/api/v1/demo/swagger.json?token=demo_token&db=source', http_client=http_client ) result = odoo.res_partner.callMethodForResPartnerModel( method_name="search", body={ 'args': [[('email', '=', 'sync@it-projects.info')]] } ).response().incoming_response.json() partner_id = result and result[0] if not partner_id: result = odoo.res_partner.addResPartner(body={ "name": "OpenAPI Support", "email": "sync@it-projects.info" }).response().result partner_id = result.id odoo.res_partner.callMethodForResPartnerSingleRecord( id=partner_id, method_name="message_post", body={ "kwargs": { "body": "The Openapi module works in Python! Thank you!", "partner_ids": [partner_id] } } ).response()
Comming soon...
Comming soon...
Comming soon...
Comming soon...
Comming soon...
You may send this page to your IT guys to evaluate the possibilities or just tell us your concerns: help@itpp.dev
Let our expertise work for you!
(Doors and windows below are clickable)
/itpp-labs-1100.jpg)
/itpp-labs-930.jpg)
/itpp-labs-690.jpg)
REST API/Openapi/Swagger
Installation
Install this module in a usual way
Add openapi to --load parameter, e.g.:
./odoo-bin --workers=2 --load openapi,web --config=/path/to/odoo.conf
Configuration
Activating and customization
Open menu [[ OpenAPI ]] >> OpenAPI >> Integrations
Click [Create]
Specify Name for integration, e.g. test
Set Log requests to Full
Set Log responses to Full
In Accessable models tab click Add an item
Set Model, for example res.users
Configure allowed operations
[x] Create via API
- Set Creation Context Presets, for example
- Name: brussels
- Context: {'default_tz':'Europe/Brussels', 'default_lang':'fr_BE'}
- Set Creation Context Presets, for example
[x] Read via API
Set Read One Fields -- fields to return on reading one record
Set Read Many Fields -- fields to return on reading multiple records
Note: you can use Export widget in corresponding Model to create Fields list. To do that:
- Open menu for the Model
- Switch to list view
- Select any record
- click [Action] -> Export
- Set Export Type to Export all Data
- Add the fields you need to right column
- Click Save fields list, choose name and save the list
- Now the list is availab to set Read One Fields, Read Many Fields settings
[x] Update via API
[x] Delete via API
Click [Save]
Copy Specification Link to use it in any system that support OpenAPI
Authentication
- Activate Developer Mode
- Open menu [[ Settings ]] >> Users >> Users
- Select a user that will be used for iteracting over API
- In Allowed Integration select some integrations
- Copy OpenAPI Token to use it in any system that support OpenAPI
Usage
As the simplest example, you can try API in Swagger Editor. It allows to review and check API
- Open http://editor.swagger.io/
- Click menu File >> Import File
- Set Specification link
- RESULT: Specification is parsed succefully and you can see API presentation
- Click [Authorize] button
- Username -- set database name
- Password -- set OpenAPI Token (how to get one is described in authentication above)
- Note:
The Swagger Editor sends requests directly from browser which leads to CORS error and work with it is not available in odoo.sh. The easiest solution is to simply copy-past the curl command from Swagger Editor and run it from the terminal.
Alternatively, you can grant CORS headers in your web server. Below is example for Nginx:
location /api/v1 { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*' 'always'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH' 'always'; add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' 'always'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*' 'always'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH' 'always'; add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' 'always'; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*' 'always'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH' 'always'; add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' 'always'; } if ($request_method = 'PUT') { add_header 'Access-Control-Allow-Origin' '*' 'always'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH' 'always'; add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' 'always'; } if ($request_method = 'DELETE') { add_header 'Access-Control-Allow-Origin' '*' 'always'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH' 'always'; add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' 'always'; } if ($request_method = 'PATCH') { add_header 'Access-Control-Allow-Origin' '*' 'always'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH' 'always'; add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' 'always'; } # ... }
How to call methods with arguments via API
Here is an example of calling a search method with domain.
This is how it is usually done from python code:
partner_ids = self.env["res.partner"].search([("is_company", "=", "True")])
On using API it would be as following:
curl -X PATCH "http://example.com/api/v1/demo/res.partner/call/search" -H "accept: application/json" \ -H "authorization: Basic BASE64_ENCODED_EXPRESSION" -H "Content-Type: application/json" \ -d '{ "args": [[["is_company", "=", "True" ]]]}'
Updating existing record
For example, to set phone value for a partner, make a PUT request in the following way:
curl -X PUT -H "Authorization: Basic BASE64_ENCODED_EXPRESSION" \ -H "Content-Type: application/json" -H "Accept: */*" \ -d '{ "phone": "+7123456789"}' "http://example.com/api/v1/demo/res.partner/41"
To set many2one field, you need to pass id as a value:
curl -X PUT -H "Authorization: Basic BASE64_ENCODED_EXPRESSION" \ -H "Content-Type: application/json" -H "Accept: */*" \ -d '{ "parent_id": *RECORD_ID*}' "http://example.com/api/v1/demo/res.partner/41"
For more examples visit https://itpp.dev/sync website
Please log in to comment on this module
Report comment
Any abuse of this reporting system will be penalizedI cann't install module, odoo notification "Unable to install module "openapi" because an external dependency is not met: No module named bravado_core". help me! Thanks.
Re: I cann't install module, odoo notification "Unable to install module "openapi" because an external dependency is not met: No module named bravado_core". help me! Thanks.
Hello,
you need to install the next python dependencies: bravado and swagger-spec-validator==2.4.3
Contact us via support e-mail if you have any more questions: help@itpp.dev
Regards,
Denis
Usefull to enable REST API in Odoo
This module is working well. I had difficulties at the beginning with small bugs, but the support team answered very quickly. The documentation is very light but does the job. The module is not perfect but worth the 4 stars and is ok for production server.
Re: Usefull to enable REST API in Odoo
Hello,
thanks for the feedback provided. We continue to work on the module and with your support, it will definitely get better
Best regards
I cann't install module, I already install the python dependencies bravado-core and swagger-spec-validator==2.4.3, but it does not work, help please
Erro:
Odoo Server Error
Traceback (most recent call last):
File "/opt/odoo/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
result = request.dispatch()
File "/opt/odoo/odoo/http.py", line 682, in dispatch
result = self._call_function(**self.params)
File "/opt/odoo/odoo/http.py", line 358, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/opt/odoo/odoo/service/model.py", line 94, in wrapper
return f(dbname, *args, **kwargs)
File "/opt/odoo/odoo/http.py", line 346, in checked_call
result = self.endpoint(*a, **kw)
File "/opt/odoo/odoo/http.py", line 911, in __call__
return self.method(*args, **kw)
File "/opt/odoo/odoo/http.py", line 530, in response_wrap
response = f(*args, **kw)
File "/opt/odoo/addons/web/controllers/main.py", line 1359, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/opt/odoo/addons/web/controllers/main.py", line 1351, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/opt/odoo/odoo/api.py", line 396, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/opt/odoo/odoo/api.py", line 383, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "/opt/odoo/odoo/models.py", line 6145, in onchange
value = record[name]
File "/opt/odoo/odoo/models.py", line 5620, in __getitem__
return self._fields[key].__get__(self, type(self))
File "/opt/odoo/odoo/fields.py", line 973, in __get__
self.compute_value(recs)
File "/opt/odoo/odoo/fields.py", line 1112, in compute_value
records._compute_field_value(self)
File "/opt/odoo/odoo/models.py", line 4020, in _compute_field_value
getattr(self, field.compute)()
File "/opt/data-dir/addons/14.0/openapi/models/openapi_namespace.py", line 263, in _compute_log_count
"SELECT COUNT(*) FROM openapi_log WHERE namespace_id=(%s);", [str(self.id)]
File "<decorator-gen-3>", line 2, in execute
File "/opt/odoo/odoo/sql_db.py", line 101, in check
return f(self, *args, **kwargs)
File "/opt/odoo/odoo/sql_db.py", line 296, in execute
res = self._obj.execute(query, params)
Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/odoo/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/opt/odoo/odoo/http.py", line 314, in _handle_exception
raise exception.with_traceback(None) from new_cause
psycopg2.DataError: invalid input syntax for integer: "NewId_0x7fec648b0c18"
LINE 1: ...ECT COUNT(*) FROM openapi_log WHERE namespace_id=('NewId_0x7...
^
I cann't install module, odoo notification "Unable to install module "openapi" because an external dependency is not met: No module named bravado_core". help me! Thanks.
Re:
Hello,
you need to install the next python dependencies: bravado and swagger-spec-validator==2.4.3
Contact us via support e-mail if you have any more questions: help@itpp.dev
Regards,
Denis
I get following error when installing:
Error:
Uncaught Error: QWeb2: Template 'DashboardOpenAPI' not found
Update about odoo.sh
The module does work in odoo.sh To modify server_wide_modules parameter * navigate to Shell tab in odoo.sh * execute nano .config/odoo/odoo.conf * add server_wide_modules parameter with openapi added. For odoo 12 it's as following: server_wide_modules=base,web,openapi * restart server by executing following command: odoosh-restart
Can i use this API in Odoo sh?
Does this API support in odoo sh?
Re: Can i use this API in Odoo sh?
The installation instruction requires to add "openapi" to --load parameter in odoo run command or server_wide_modules in odoo config file. But odoo.sh doesn't allow to modify those settings. Without those settings it may have issues, e.g. first request to API may not work. You may contact the support team at odoo.sh and ask for possibility to modify those settings