Implementation of Common API Methods in Odoo 15

Implementation of Common API Methods in Odoo 15

2 minutes, 4 seconds Read

An API which stands for application programming interface performs as a connection between computers or between computer programs. Odoo is an open ERP software written in python. API methods like Get, post, put, delete, etc can also be implemented in Odoo. We can create records in Odoo by retrieving data through the API GET method. Also, we can send data through the API POST method simultaneously with record creation. 

We can simply implement these methods for any model by supering create, write, unlink, etc.

In this blog, let us discuss some of the common API methods and their implementation in Odoo.

The common API methods are listed below.

1. Get Method

To get data from an API.

E.g.:

data = {}
url = "http://example.com"
response = requests.get(url, data=json.dumps(data))

E.g.: We can get data from an API and create records in Odoo using the retrieved data from the API. From Odoo import fields, models, API

import json
import requests
class ModuleName(models.Model):
_name = 'module.name'
_description = 'Module Description’'
name =  fields.Char(string=”Name”)
age =  fields.Char(string=”Age”)
def get_data(self):
    data = {}
    url = “http://example.com”
    response = requests.get(url, data=json.dumps(data))
        res = response.json()
        values = {
            "name": res.get('Name'),
            "age": res.get('Age')
        }
    super(ModuleName, self).sudo().create(values)

2. Post Method

To send data to an API

E.g.: Let’s look at how to send data to an API when creating a record/data in Odoo, from Odoo import fields, models, API

import json
import requests
class ModuleName(models.Model):
_name = 'module.name'
_description = 'Module Description’'
name =  fields.Char(string=”Name”)
age =  fields.Char(string=”Age”)
@api.model
def create(self, vals):
data = {
“Name” : vals.get(‘name’),
“Age” : vals.get(‘age’’),
}
url = ""http://example.com"
response = requests.post(url, data=json.dumps(data))
return super(ModuleName, self).create(vals)

3. Put Method

To Update/Edit existing data.

E.g.: Let’s look at how to update data when editing a record/data in Odoo, Assume  “link” as the URL of the record we want to update. Then,

def write(self, vals):
    record  = super(moduleName, self).write(vals)
    data = {
        "Name": self.name,
        "Age": self.age,
            }
    response = requests.put(link, data=json.dumps(data))
    return record

4. Delete Method

To remove/Delete data.

E.g.: Let’s take “url” as the URL of the record we want to delete. Then,

Payload = {}
headers = {}
response = requests.request("DELETE", url, headers=headers, data=payload)

After performing all the changes, restart the module and check. This is how common API methods are implemented in odoo 15.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *