How to manage Records using API: Python sample code

How to manage Records using API: Python sample code

For those who love to do things the “API way”, we have prepared a sample Python code, which guides the developer on how to add, update and delete the Records. It is a single-run Python script doing all three things at once.

The script should be self-explanatory. All you need to do is to update the apiUser and apiPass variables, which can be taken from the “Account” -> “Integrations” -> “AutoROICalc API” section.

It uses Requests, the simple, yet elegant, HTTP library.

The script starts with defining the API URLs: to add, update and delete Records. Following is the sample Records array. The first API call is adding the sample Records. The original sample Records array is updated with the ids of the Records that were added and also the Records values are changed. Next, it updates those Records and finally, the sample Records are deleted:

# https://pypi.org/project/requests/
import requests
from requests.auth import HTTPBasicAuth
import json

# API urls, user and password
urlAdd = "https://autoroicalc.com/api/auto-roi-calc/v1/add-records"
urlUpdate = "https://autoroicalc.com/api/auto-roi-calc/v1/update-records"
urlDelete = "https://autoroicalc.com/api/auto-roi-calc/v1/delete-records"

apiUser = "<YOUR_API_USERNAME>"
apiPass = "<YOUR_API_PASSWORD>"

records = [
  {
    "date": "2021-04-04",
    "time": "16:35",
    "type": "exampleType",
    "activity": "closed",
    "desc": "exampleDescription",
    "source": ["exampleSource1", "exampleSource2"],
    "value": 13.94
  },
  {
    "date": "2021-04-05",
    "time": "12:09",
    "type": "exampleType",
    "activity": "closed",
    "desc": "exampleDescription",
    "source": ["exampleSource1"],
    "value": 20.21
  }
]

# ADD RECORDS
response = requests.post(
  urlAdd,
  json = records,
  auth = HTTPBasicAuth(apiUser, apiPass)
)
print("Status code:", response.status_code)
print(response.text)

# collect IDs of the added records to demonstrate update
idsToUpdate = []
for result in json.loads(response.text)["results"]:
  idsToUpdate.append(result["recordId"])

# update the original records structure with the retrieved record ids
# nudge the records value
records[0]["id"] = idsToUpdate[0]
records[0]["value"] = 1
records[1]["id"] = idsToUpdate[1]
records[1]["value"] = 2

# UPDATE RECORDS
response = requests.put(
  urlUpdate,
  json = records,
  auth = HTTPBasicAuth(apiUser, apiPass)
)
print("Status code:", response.status_code)
print(response.text)

# DELETE RECORDS
response = requests.delete(
  urlDelete,
  json = idsToUpdate,
  auth = HTTPBasicAuth(apiUser, apiPass)
)
print("Status code:", response.status_code)
print(response.text)

Posted

in

Explore the Records-related tutorials:

Explore the Reports-related tutorials

Explore the Dashboards-related tutorials