Example sending custom data to the API using Python
The following example demonstrates how to connect to the TeleTracking API using Python and the requests
library. This sample shows how to send data to a specific endpoint using a POST
request.
import requests
baseUrl = "https://teletracking.app/api"
result = requests.post(
url = f"{baseUrl}/customdatareceiver/externalcustomdata",
verify = False,
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {accessToken}"
},
data = payload
)
Make sure to replace accessToken
with your actual bearer token and payload
with the appropriate JSON-formatted data for your request.
Note: verify=False
is used to bypass SSL certificate verification in this example. In production environments, it’s strongly recommended to enable SSL verification.
Retrieving an Access Token in Python
Before making requests to the TeleTracking API, you must first authenticate by retrieving an access token. The following Python example demonstrates how to construct the request and retrieve the token using the requests
library.
import requests
def getAccessToken():
getaccesstoken = {
"header": {
"sourceId": sourceId,
"tenantId": tenantId,
"userId": userId
},
"body": {
"key": token
}
}
tokenholder = requests.post(
url = f"{baseUrl}/getaccesstoken",
headers = {"Content-Type": "application/json"},
json = getaccesstoken
)
return tokenholder.json()["accessToken"]
Parameters to Replace:
sourceId
,tenantId
,userId
: Values provided by your organization or API admin.token
: Your authentication key (e.g., application token or secret).
Note: Ensure that baseUrl
is defined as https://teletracking.app/api
prior to making the request.
After retrieving the token, you can use it as a Bearer token in the Authorization
header for any subsequent API calls.
Constructing a Payload for Submitting Custom Data
The following Python example demonstrates how to build a JSON payload for submitting custom data to the TeleTracking API. The payload includes both header metadata and a body section containing the data to be sent.
from json import dumps
from uuid import uuid4
from datetime import datetime
nowTime = datetime.utcnow().isoformat() + "Z"
payload = dumps({
"header": {
"id": str(uuid4()),
"schemaUri": "https://sv.telesv.com/schemas/CreateExternalCustomData_v1.001.json",
"version": "1.001",
"command": "CreateExternalCustomData",
"sourceId": sourceId,
"correlationId": str(uuid4()),
"tenantId": tenantId,
"dateTime": nowTime,
"userId": userId,
"ttl": 100000
},
"body": this_patient_info
})
Parameters to Replace:
sourceId
,tenantId
,userId
: Values provided by your organization or API admin.this_patient_info
: The actual data you want to submit (e.g., patient details).schemaUri
,command
,version
, andttl
: Provided by your integration or schema documentation.
Note: Ensure your payload is passed into the data
field of your request when sending data using requests.post()
.
Handling API Errors in Python
The following snippet demonstrates how to log and handle HTTP response status codes when making requests to the TeleTracking API using the requests
library.
import requests
response = requests.post(
url=f"{baseUrl}/customdatareceiver/externalcustomdata",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {accessToken}"
},
data=payload
)
# Basic error handling
if response.status_code == 200:
print("Request successful.")
else:
print(f"Request failed with status code {response.status_code}")
print("Response content:", response.text)
Optional (Recommended): Raise and Catch Exceptions
For more robust error handling, you can use raise_for_status()
and a try/except block:
try:
response = requests.post(
url=f"{baseUrl}/customdatareceiver/externalcustomdata",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {accessToken}"
},
data=payload
)
response.raise_for_status() # Raises HTTPError for bad responses
print("Request successful:", response.json())
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print("Response content:", response.text)
except Exception as err:
print(f"Other error occurred: {err}")
Optional: Simple Approach
You could retry the request once or twice, log any failures or errors to a log file, and keep those logs for around 30 days or based on available storage.