Python Example
Example of a python request and response for model inference using python's request library
Contents
Python POST Request
Imports
The easiest way to interact with APIs in python is using the requests library.
import requests
import json
Headers
Define the 3 headers in a dictionary.
The model specific values can be found 👉 here
headers = {
"Content-Type": "application/json",
"x-corsali-organization-id" : "irjt4o3t-....",
"Authorization" : "Bearer eyJxxx.eyJxxx.1ANxxx"
}
URL
Define the url.
https://api.corsali.com/predict/ is the base URL
"fe9e3jpl2-23z8-..." is an example model id
For a list of model ids associated with your organization see 👉 here
url = "https://api.corsali.com/predict/fe9e3jpl2-23z8-..."
JSON
Define your payload data.
This can be done directly in python or as a file passed in. If we define our JSON directly in python we need to convert the data to json using
json.dumps
#Define directly
payload = {"example": "json_data","exampleFloat":4}
payload = json.dumps(payload)
#Or pass in a JSON file
payload = open('example.json', 'rb').read()
Post Request
Make a post request by passing in your url, headers, and payload data if it was defined directly in python.
r = requests.post(url,headers=headers,data=payload)
Python Response
Get the response as a JSON object which can then be used as python dictionary. We first check if the query was successful. This is because error messages are strings not JSONs.
#Check response status
if r.status_code == requests.codes.ok:
#Responses are returned as JSON
response = r.json()
#Can index on JSON object like a dictionary
response_data = response["data"]
else:
#Errors are returned as text
error = r.text
Full Code
To run the code below, fill in the organization id, model id, authentication key, and file name.
import requests
import json
#User Specific inputs
organization_id = ""
model_id = ""
authentication_key = ""
file_name = ""
#Headers
headers = {
"Content-Type": "application/json",
"x-corsali-organization-id" : organization_id,
"Authorization" : "Bearer {Authentication_Key}".format(Authentication_Key=authentication_key)
}
#URL
url = "https://api.corsali.com/predict/{Model_Id}".format(Model_Id = model_id)
#JSON
payload = open(file_name, 'rb').read()
#Post Request
r = requests.post(url,headers=headers,data=payload)
#Check response status
if r.status_code == requests.codes.ok:
#Responses are returned as JSON
response = r.json()
#Can index on JSON object like a dictionary
response_data = response["data"]
print(response_data)
else:
#Errors are returned as text
error = r.text
print(error)
Last updated
Was this helpful?