Web APIs
Pro features are only available with a Professional licence. To upgrade, visit cavalry.scenegroup.co.
Introduction
Cavalry provides a way to interact with API endpoints on the web by creating a WebClient
object and interacting with its methods to get
, post
or put
. These API calls are blocking meaning they must successfully complete before progressing to the next part of a script.
Further to the WebClient
, Cavalry also provides a simple WebServer
. You can call /get
to retrieve whatever response you have set on the server, or, for those of an adventurous persuasion, you can use /post
. To aid when using /post
the WebServer
can poll for new data and will fire a callback function when a data drop has been detected.
Getting Started
Try these examples to get to know the Web API.
Simple get
request.
// Make a new WebClient
var client = new api.WebClient("https://www.boredapi.com");
// Send the Get Request (this returns a random activity to do if you're bored).
client.get("/api/activity");
// Check it succeeded
if (client.status() == 200) {
let obj = JSON.parse(client.body());
// Safety check, and print the activity
if ('activity' in obj) {
console.log("Random activity: "+obj.activity);
}
}
Getting and saving an SVG file.
var client = new api.WebClient("https://cavalry.scenegroup.co");
client.get("/images/logo_cavalry-landscape-outline_001.svg");
if (client.status() == 200) {
api.writeToFile("/Some/Path/Here/cavLogo.svg", client.body());
}
WebClient
When using the WebClient the constructor can only contain the base URL (e.g. https://www.boredapi.com). Passing in a route (e.g. https://www.boredapi.com/api/activity) results in an error where WebClient.status()
will return -1
.
setBasicAuthentication(username:string, password:string)
Sets basic authentication for any subsequent requests.
setDigestAuthentication(username:string, password:string)
Sets digest authentication for any subsequent requests.
setTokenAuthentication(token:string)
Sets token based authentication for any subsequent requests.
addHeader(key:string, value:string)
Adds a header for any following requests. API keys, app keys, content types and so forth can be added in this way.
getHeaders() → object
var client = new api.WebClient("https://www.boredapi.com");
client.get("/api/activity");
if (client.status() == 200) {
let headers = client.getHeaders();
for (const [key, value] of Object.entries(headers)) {
console.log(`${key}: ${value}`);
}
}
status() → int
Returns the status of the request. For example 200 means OK
.
body() → string
The returned body. This is often in the form of JSON but you can check the Content-Type
header with getHeaders()
if you're unsure.
get(path:string)
Performs a get
request. Once done, status()
and if successful, body()
should be available.
post(path:string, content:string, contentType:string)
Performs a post
request. Once done, status()
and if successful, body()
should be available.
put(path:string, content:string, contentType:string)
Performs a put
request. Once done, status()
and if successful, body()
should be available.
postFromFile(path:string, filePath:string, contentType:string)
A helper method for posting a file directly. This method is needed especially when uploading binary files (like images or movies).
Performs a post
request. Once done, status()
and if successful, body()
should be available.
putFromFile(path:string, filePath:string, contentType:string)
A helper method for posting a file directly. This method is needed especially when uploading binary files (like images or movies).
Performs a put
request. Once done, status()
and if successful, body()
should be available.
writeBodyToBinaryFile(path:string)
If get
has been used to retrieve binary data (i.e an image or a movie), this cannot be passed to the usual api.writeToFile()
call. You must instead use this function to write the body data to file (which you can then pull into Cavalry as an Asset for example).
setProxy(hostAddress:string, port:number)
Enter a proxy server's IP and port number.
setProxyBasicAuthentication(username:string, password:string)
Enter a username and password to authenticate to a proxy server.
setProxyBearerAuthentication(password:string)
Enter a password for a proxy server that uses a bearer token.
WebServer
A complete example of a UI script which implements a Cavalry Server. Please save this into the Cavalry Scripts folder Help > Scripts
and then load it via the Window > Scripts
menu.
var server = new api.WebServer();
var button = new ui.Button("Start Server");
button.onClick = function () {
if (!server.isRunning()) {
server.listen("localhost", 1234);
button.setText("Stop Server");
} else {
server.stop();
button.setText("Start Server");
}
}
function Callbacks() {
this.onPost = function () {
console.log("Queue length: "+server.postCount());
processButton.setEnabled(true);
}
}
var processButton = new ui.Button("Process Posts");
processButton.setEnabled(false);
processButton.onClick = function () {
while(server.postCount()) {
let obj = server.getNextPost();
console.log("Process: "+obj.result);
}
processButton.setEnabled(false);
}
var callbackObj = new Callbacks();
server.addCallbackObject(callbackObj);
ui.add(button);
ui.add(processButton);
ui.show();
Once this script is running, run this in the JavaScript Editor, the /post
text should print to the console.
var client = new api.WebClient("http://localhost:1234");
client.post("/post", "Cavalry Needs You!", "text/plain");
client.post("/post", "Join the Cavalry!", "text/plain");
listen(host:string, port:int)
Start the server listening on the host address (e.g localhost
) on the specified port number.
stop()
Stop the server, any polling will also stop.
setResultForGet(resultText:string)
Set the result for /get
requests, only text/plain
is currently supported.
getNextPost() → object
As many /post
events may happen before you have a chance to react, Cavalry will queue them for you.
This function will get the next (the oldest) post and will pop the post from the queue meaning once you get it, you can no longer access it from the server.
The object will contain a result
string, and an headers
array, each header is an object with a name
and value
. Please note only non binary data is supported for /post
events.
getNewestPost() → object
This is just like the above method, only instead of getting the oldest unprocessed /post
, it will skip to the newest and pop that from the queue.
postCount() → int
Returns the number of unprocessed /post
events. Process posts using the getNextPost()
or getNewestPost()
functions.
clearPosts()
Clear all unprocessed /post
events. Process posts using the getNextPost()
or getNewestPost()
functions.
addCallbackObject(callbackObj:object)
Set a Callback object (much like the UI callback object). This is a JavaScript object with an onPost
function implemented.
Setting a Callback object will start the server polling for new information, by default we poll the server once every 3 seconds.
var server = new api.WebServer();
function Callbacks() {
this.onPost = function () {
console.log("Check result: " + server.getNewestPost().result);
}
}
var callbackObj = new Callbacks();
server.addCallbackObject(callbackObj);
setHighFrequency()
Calling this after setting a Callback object will change the polling frequency to once per second.
setRealtime()
Calling this after setting a Callback object will change the polling frequency to 60 times a second. This is useful for realtime communication with things like midi-controllers.