OctoPrintClient
- class OctoPrintClient([options])
Instantiates a new instance of the client library. Note that by default there’s always an instance registered globally called
OctoPrint
.- Arguments
options (
object()
) – An optional object of options to setOctoPrintClient.options
to.
- OctoPrintClient.options
The client library instance’s options. The following keys are currently supported:
baseurl
The base URL of the OctoPrint API
apikey
The API Key to use for requests against the OctoPrint API. If left unset, you’ll need to authenticate your session through a login.
locale
The locale to set in
X-Locale
headers on API requests. Useful for API endpoints that might return localized content.
- OctoPrintClient.plugins
Registration of client library components provided by plugins.
OctoPrint plugins should always register their client classes here using their plugin identifier as key via
OctoPrintClient.registerPluginComponent()
.Note
The registration mechanism has changed slightly with OctoPrint 1.3.2 due to an otherwise unsolvable issue with allowing multiple clients to exist concurrently and still keeping the existing architecture intact.
The old mechanism works fine as long as you are only planning to offer your plugin client implementation on the default client instance
OctoPrint
, however if you also want to support additional clients you’ll need to use the implementation and registration approach as described below.Example:
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["OctoPrintClient"], factory); } else { factory(window.OctoPrintClient); } })(window || this, function(OctoPrintClient) { var MyPluginClient = function(base) { this.base = base; }; MyPluginClient.prototype.someFunction = function() { // do something }; // further define API OctoPrintClient.registerPluginComponent("myplugin", MyPluginClient); return MyPluginClient; });
- OctoPrintClient.getBaseUrl()
Returns the canonical base URL to use for OctoPrint’s API. Uses the current value of
OctoPrint.options.baseurl
. If that doesn’t end in a/
, a trailing/
will be appended to the URL before the result is returned.- Returns string
The base url to use to access OctoPrint’s API.
- OctoPrintClient.getCookie(name)
New in version 1.8.3.
Returns the value of the cookie with name
name
. The port based cookie suffix and if necessary also the script root based suffix will be automatically applied to thename
prior to looking up the value.- Return string
The value of the cookie, if set & accessible, else an empty string.
- OctoPrintClient.getRequestHeaders(method, additional, opts)
Changed in version 1.8.3.
Generates a dictionary of HTTP headers to use for API requests against OctoPrint with all necessary headers and any additionally provided ones.
At the moment this entails setting the
X-Api-Key
header based on the current value ofOctoPrint.options.apikey
, if set. Otherwise, for non-cross-domain requests targeting methods other thanGET
,HEAD
orOPTIONS
, the current CSRF token is read from the associated cookie and set asX-CSRF-Token
.Note
Up until OctoPrint 1.8.3, this method’s signature consisted only of the
additional
parameter. It has been changed in a backward compatible way so that calling it with the first parameter being the set of additional headers will still work. This mode of operation is deprecated however and will be removed in a future version. A warning will be logged to the debug console accordingly.- Arguments
method (
str()
) – Method of the request for which to set headersadditional (
object()
) – Additional headers to add to the request, optional.opts (
object()
) – Additional opts passed to the request, used to read cross domain setting, optional.
- Returns object
HTTP headers to use for requests.
- OctoPrintClient.ajax(method, url, opts)
Performs an AJAX request against the OctoPrint API, utilizing jQuery’s own ajax function.
The HTTP method to use may be defined through
opts.method
or - if that is not provided – through themethod
parameter. If neither is available,GET
will be used.The URL to perform the request against may be defined through
opts.url
or – if that is not provided – through theurl
parameter. If neither is available, an empty string will be used (plain base URL). If the URL starts withhttp://
orhttps://
it will be used directly. Otherwise the return value ofOctoPrint.getBaseUrl()
will be prepended.As headers everything returned by
OctoPrint.getRequestHeaders()
will be used. Additional headers to set may be defined by providing them throughopts.headers
.If
opts.dataType
is set, it will be used for setting the corresponding option on the jQueryajax
call, otherwisejson
will be used.Anything provided in the
opts
parameter will also be passed on to the jQueryajax
call.- Arguments
method (
string()
) – The HTTP method to use for the request (optional)url (
string()
) – The URL to perform the request against (optional)opts (
object()
) – Additional options to use for the request, see above for details (optional)
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.ajaxWithData(method, url, data, opts)
Performs an AJAX request against the OctoPrint API, including the provided
data
in the body of the request.Utilizes
OctoPrint.ajax()
, see that for more details.- Arguments
method (
string()
) – The HTTP method to use for the request (optional)url (
string()
) – The URL to perform the request against (optional)data (
object()
) – The data to send in the request body (optional)opts (
object()
) – Additional options to use for the request (optional)
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.get(url, opts)
Performs a
GET
request againsturl
.Example:
OctoPrint.get("api/version") .done(function(response) { console.log("API:", response.api, "Server:", response.server); });
- Arguments
url (
string()
) – URL against which to make the request, relative to base url or absoluteopts (
object()
) – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.getWithQuery(url, data, opts)
Performs a
GET
request againsturl
using the provideddata
as URL query.Example:
// this should perform a GET of "api/timelapse?unrendered=true" OctoPrint.getWithQuery("api/timelapse", {"unrendered": true});
- Arguments
url (
string()
) – URL against which to make the request, relative to base url or absolutedata (
object()
) – An object containing the key/value pairs of the query data OR a string representation of the queryopts (
object()
) – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.post(url, data, opts)
Performs a
POST
request againsturl
using the provideddata
as request body.Example:
var url = OctoPrint.getBlueprintUrl("myplugin") + "endpoint"; OctoPrint.post(url, "a whole lot of data", {"contentType": "application/octet-stream"}) .done(function(response) { // do something with the response });
- Arguments
url (
string()
) – URL against which to make the request, relative to base url or absolutedata (
string()
) – Data to post as request bodyopts (
object()
) – Additional options for the requestopts – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.postJson(url, data, opts)
Performs a
POST
request againsturl
using the provideddata
object as request body after serializing it to JSON.Example:
var url = OctoPrint.getBlueprintUrl("myplugin") + "endpoint"; OctoPrint.postJson(url, {"someKey": "someValue"}) .done(function(response) { // do something with the response });
- Arguments
url (
string()
) – URL against which to make the request, relative to base url or absolutedata (
object()
) – Data to post as request body after serialization to JSONopts (
object()
) – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.put(url, data, opts)
Performs
PUT
request againsturl
using the provideddata
as request body.See
OctoPrint.post()
for details.
- OctoPrintClient.putJson(url, data, opts)
Performs
PUT
request againsturl
using the provideddata
as request body after serializing it to JSON.See
OctoPrint.postJson()
for details.
- OctoPrintClient.patch(url, data, opts)
Performs
PATCH
request againsturl
using the provideddata
as request body.See
OctoPrint.post()
for details.
- OctoPrintClient.patchJson(url, data, opts)
Performs
PATCH
request againsturl
using the provideddata
as request body after serializing it to JSON.See
OctoPrint.postJson()
for details.
- OctoPrintClient.delete(url, opts)
Performs a
DELETE
request againsturl
.- Arguments
url (
string()
) – URL against which to make the request, relative to base url or absoluteopts (
object()
) – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.download(url, opts)
Downloads a file from
url
, returning the response body as data typetext
.Use this if you need to download a file from the server in order to process it further in the client. The response body returned on successful completion of the returned jQuery Promise will contain the requested file as raw string/binary.
- Arguments
url (
string()
) – URL to downloadopts (
object()
) – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.upload(url, file, filename, additional)
Uploads a
file
tourl
using amultipart/form-data
POST
request.file
should be either ofa jQuery element pointing at a file input of the page of which the first File instance will be used,
a string usable as selector to address a file input of the page of which the first File instance will be used or
If
filename
is provided, the file upload data will contain its value as file name for the upload, otherwise thename
property from the File instance.The function will return a jQuery Promise which will also be notified on the upload progress with an object containing the following properties:
- loaded
The number of bytes already uploaded
- total
The total number of bytes to upload
This can be used to populate progress bars or other types of progress visualization.
It is important to note that contrary to all the other request methods in this module,
OctoPrint.upload
is implemented usingXMLHttpRequest
directly instead of relying on jQuery’sajax
function. It still tries to replicate its behaviour on the returned jQuery Promise however, meaning that theresolve
andreject
methods will be called with(data, textStatus, request)
and(request, textStatus, error)
parameters respectively.Additional form elements for the POSTed form can be supplied through the
additional
parameters. This should be an object of key/value pairs that are set as field name and value on the FormData object that will be used in the request.Example:
Uploading a file to
some/path
on the blueprint of pluginmyplugin
, from a file input element, updating a label with the current upload progress.var fileInput = $("#my-file-input"); var progressOutput = $("#progress-output"); OctoPrint.upload(OctoPrint.getBlueprintUrl("myplugin") + "some/path", fileInput, "myfilename.dat", {"somekey": "somevalue"}) .progress(function(data) { if (data.total) { var percentage = Math.round(data.loaded * 100 / data.total); if (percentage || percentage == 0) { progressOutput.text(percentage + "%"); return; } } progressOutput.text(""); }) .done(function(response, textStatus, request) { progressOutput.text("Uploaded!"); });
- Arguments
url (
string()
) – URL to which to POST the upload, relative to base url or absolutefile (
object()
) – The file to object, see description for detailsfilename (
string()
) – An optional file name to use for the uploadadditional (
object()
) – An optional object of additional key/value pairs to set on the uploaded form data
- OctoPrintClient.issueCommand(url, command, payload, opts)
Issues a command against an OctoPrint command API endpoint.
OctoPrint contains various API endpoints which follow a specific pattern: The payload of the request body is a JSON object which contains at least one property
command
and depending on the provided command additional parameters as further properties for the command. See the Issue a file command for an example of an API endpoint following this pattern.Using this function sending commands to such API endpoints becomes a trivial task. The function expects the
url
of the endpoint, thecommand
to send, and optionalpayload
and additionalopts
.The function will take care of wrapping the
command
and thepayload
into one JSON object and POSTing that to the endpoint with the correct JSON content type.Example:
var url = OctoPrint.getBlueprintUrl("myplugin") + "myendpoint"; OctoPrint.issueCommand(url, "mycommand", {"someParameter": "someValue", "someOtherParameter": "someOtherValue"}) .done(function(response) { // do something with the response });
- Arguments
url (
string()
) – The URL toPOST
the command tocommand (
string()
) – The command to issuepayload (
object()
) – Additional payload data for the commandopts (
object()
) – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.getSimpleApiUrl(plugin)
Returns the proper URL for the endpoint of a
SimpleApiPlugin
, based on the plugin identifier.Example:
// prints "api/plugin/myplugin" console.log(OctoPrint.getSimpleApiUrl("myplugin")
- Arguments
plugin (
string()
) – The identifier of the plugin for which to return the URL
- Returns string
The URL to use as endpoint
- OctoPrintClient.simpleApiGet(plugin, opts)
Performs a
GET
request against the endpoint of aSimpleApiPlugin
with identifierplugin
.OctoPrint.simpleApiGet("myplugin") .done(function(response) { // do something with the response });
- Arguments
plugin (
string()
) – The identifier of the pluginopts (
object()
) – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.simpleApiCommand(plugin, command, payload, opts)
Performs the API command
command
against the endpoint of aSimpleApiPlugin
with identifierplugin
, including the optionalpayload
.Example:
OctoPrint.simpleApiCommand("myplugin", "mycommand", {"someParameter": "someValue", "otherParameter": "otherValue"}) .done(function(response) { // do something with the response });
- Arguments
plugin (
string()
) – The identifier of the plugincommand (
string()
) – The command to issuepayload (
object()
) – Additional payload data for the commandopts (
object()
) – Additional options for the request
- Returns Promise
A jQuery Promise for the request’s response
- OctoPrintClient.getBlueprintUrl(plugin)
Returns the proper base URL for blueprint endpoints of a
BlueprintPlugin
with identifierplugin
.Example:
// prints "plugin/myplugin/" console.log(OctoPrint.getBlueprintUrl("myplugin"));
- OctoPrintClient.createRejectedDeferred()
Static method.
Shortcut for creating a rejected jQuery Deferred.
- OctoPrintClient.createCustomException(name)
Static method.
Creates a custom exception class.
name
may be either a function in which case it will be used as constructor for the new exception class, or a string, in which case a constructor with propername
,message
andstack
attributes will be created. The class hierarchy will be properly setup to subclassError
.Example:
MyCustomException = OctoPrintClient.createCustomException("MyCustomException"); throw new MyCustomException("Something went horribly wrong!");
- OctoPrintClient.registerPluginComponent(identifier, clientClass)
Static method.
Registers the plugin client component
clientClass
under the nameidentifier
on theOctoPrintClient.plugins
registry.clientClass
must have a constructor that follows the signatureClientClass(base)
and in which it sets the attributebase
on the instance to:var MyPluginClient = function(base) { this.base = base; }
Each
OctoPrintClient()
will create its own instance of registered plugin classes and make them available underOctoPrintClient.plugins
. It will inject itself into those instances in order to allow plugin clients to access its functionality viathis.base
:MyPluginClient.prototype.doSomething = function(data, opts) { return this.base.simpleApiCommand("myplugin", "doSomething", data, opts); };
- Arguments
identifier (
string()
) – The identifier of the plugin for whichclientClass
is the clientclientClass (
class()
) – The client class to register. Constructor must follow the signatureClientClass(base)
wherebase
will be assigned to the instance asthis.base
and be theOctoPrintClient()
instance to use for API calls etc viathis.base
.
- class OctoPrintClient.InvalidArgumentError()
Exception to use when functions are called with invalid arguments.