This SDK can be used by browsers or the Node.js environment. However, certain methods may only be available in one environment. There will also be different functional behaviors between the two environments as well.
This document will tag methods, properties or behaviors with [web]
and
[node]
to indicate what environment they are available in.
For the convenience, the SDK object will be referred as kloudless
through this document.
-
Due to the variety of our API categories, the SDK does not abstract each type of resource in the API like most SDKs would do. Instead, the SDK provides many utilities and classes to make working with Kloudless API easier.
-
Hence, it is highly recommended that you refer to our API documentation when using this SDK. We also encourage making API requests to our Kloudless service directly through http.
-
The SDK uses axios to make API requests internally. The options schema is basically the same as axios' schema. Note that you have to put "url" and "data" in the config object. e.g. The
kloudless.post(url[, data[, config]]
alias WILL NOT work. -
axios utilizes javascript's Promise to make http requests, thus this SDK also handled API requests with Promise whenever possible.
The following objects can all make API requests with the folllowing http
methods get()
, put()
, post()
, patch()
, and delete()
:
Each method takes an options
Object as argument for request URLs and other
request parameters (see below for details).
The returned value is a Promise that will be resolved with a Response object once the request succeeds. An Exception object is thrown if the request has failed.
url
: Required: String
API endpoint URL, you can omit certain parts of URLs based on which objects you are making request with:Account
: remove 'accounts' and account ID.- Example: pass
storage/folders/{folder_id}
for/accounts/{account_id}/storage/folders/{folder_id}
- Example: pass
Response
or its subclasses: anything that is part ofurl
property- Example: for a
Resource
representing/accounts/{account_id}/cal/calenders/{calendar_id}
, you only need to passevents
forcal/calendars/{calendar_id}/events
.
- Example: for a
- DO NOT include query params in URL, use
params
option instead.
headers
: Optional: Object[key: (String|Object)]
Request headers. Some of common headers used for Kloudless API:- X-Kloudless-Raw-Headers
- X-Kloudless-Raw-Data
- X-Kloudless-As-User
- Authorization:
Required if you are making request from
kloudless
object. Optional for the other objects, as this header will be automatically filled. If the header value is an object, the SDK will attempt to convert the object into a string ofJSON.stringify()
. Hence, for JSON string headers like X-Kloudless-Metadata, you can just pass an object instead of a string.
data
: Optional: Object
Request body, if supported by the request method. The object should be one of the following types:- For JSON data, use a plain object
- For binary contents (e.g. uploading file for POST
storage/files
), use an instance of listed classes or their child classes below:[web]
:Blob
,ArrayBuffer
[node]
:Buffer
,stream.Readable
params
: Optional: Object[key: (String)] Query parameters.wrapResponse
: Optional: Object
Iffalse
, resolve promise with axios response object instead of aResponse
object.- Other axios options:
Optional
These options will be passed through axios without any processing from SDK.- Note that
baseURL
is overwritten by SDK, to set API server URL or api version, usekloudless.setBaseUrl
andkloudless.setApiVersion
.
- Note that
The Main SDK Object, it contains references to all classes provided by the SDK
described below. For example, you can create an account object by
new kloudless.Account(options)
.
This object will be available at window.Kloudless.sdk
if the SDK is installed
by using provided script tag in README.
Check the Installation Guide to see how to import the main SDK Object.
- References to all classes in SDK
axios
: The axios instance used to make API requests.
The SDK uses this axios instance to make API requests, you can utilize axios' defaults or interceptors API for your needs.version
: String: SDK version
-
[web]
connectAccount(options)
Connect an account with OAuth 2.0 Implicit Grant flow.- options (Object):
scope
: Required: String
A string to specify services, api and permissions, check API documentation for string format and examples.appId
: Required: String
Your App Id.
- options (Object):
-
[node]
getAuthorizationUrl(options)
Return a URL to connect account with OAuth 2.0 Authorization Code Grant flow, you will need to redirect user to the returned URL.- options (Object):
scope
: Required: String
A string to specify services, api and permissions, check API documentation for string format and examples.appId
: Required: String
Your App Id.redirectUri
: Required: String
The redirect Uri after the user connects an account.state
: Optional: String
A string that will be passed as part of callback URL. If not provided, the function will generate a random string and include it in the returned object.extraData
: Optional: JSON Object
Extra data needed for specific services.params
: Optional: Object
Query parameters attached to the returned URL.
- Return value: an object containing
state
andurl
.
You will need to record the returned state (e.g. into user session), this is needed to retrieve access token in the callback. CheckcompleteAuth
method below for detail.
- options (Object):
-
[node]
completeAuth(options)
Get account's Bearer Token from OAuth callback URL, this method should be called in the callback after the user connects an account.- options (Object):
appId
: Required: String
Your App Id.apiKey
: Required: String
Your API Key.redirectUri
: Required: String
TheredirectUri
passed intogetOAuthUrl
method.state
: Required: String
The state string returned bygetOAuthUrl
method.oauthCallbackUrl
: Required: String
the callback URL after connecting account sent by browser.
- Return value: A Promise resolved with the bearer token of the connected account.
- Exception: If the
state
parameter and the state inrequestUri
does not match, an exception will be thrown.
- options (Object):
-
verifyToken(options)
Verify if the token is valid / belong to this app, recommend to use if the token is not acquired from the provided methods above.- options (Object):
appId
: Required: String
Your App Id.token
: Required: String
Access token to be verified.initAccount
: Optional: Boolean
If set totrue
, a Account object is created and attached toaccount
property.
- Return value: a Promise resolved with an object containing the
following keys:
valid
: Boolean, the token is valid or not.error
: String, only provided if the token is not valid. Contains reason why the token is not valid.account
: Account, only available wheninitAccount
option istrue
.
- options (Object):
-
setBaseUrl(url)
Change API Server URL for all API requests- url: String: API server Url
-
setApiVersion(version)
Change API Version for all API requests- url: Number: API version number
An object representing an connected account.
id
: String
Account IDtoken
: String[web]
Bearer token[node]
Bearer token or API Key, depends ontokenType
property
tokenType
: String[web]
always"Bearer"
[node]
"Bearer"
or"APIKey"
data
: Object
Details of this account, this will be available oncegetDetail()
is called, it can also be specified in the constructor.defaults
: Object
Default options that will be applied to requests made from this object. The options passed into http request methods will be deep merged with default options (default options have lower priority when there are conflicts).
- constructor(options)
- options (Object):
token
: String: Required
Account Bearer tokendata
: Object: Optional
Account detail data[node]
tokenType
: String: Optional
Use `"APIKey" if you wish to use api key instead of bearer token, otherwise leave this as empty.[node]
accountId
: String: Optional
Account ID. Only required iftokenType
is"APIKey"
- options (Object):
- getDetail()
Retrieve account detail from API, the details will be stored indata
property. You don't need to call this method if the account is created by[web] kloudless.connectAccount()
or[node] kloudless.createAccountFromOAuthCallBack()
as the details are already retrieved beforehand.- Return value: a Promise resolved after account detail is retrieved.
- raw(options)
Make pass-through requests.- options (Object):
- Same as other request options
- Additional
method
: String is required to specify http method. The value should be one of these: "get", "put", "patch", "post", "delete".
- Return value and exception are the same as other request methods, but the resolved value is the response object from axios, no Response object will be created for pass-through requests.
- options (Object):
- encodeRawId(rawIdData)
Encode Raw ID.- rawIdData: Object: Required The upstream service ID to be encoded.
- Return value and exception are the same as other request methods
- API Request methods
An object to represent any response from Kloudless API
-
url
: String
The url used to make the API Request that returned this response. -
data
: Any
Response body. If the response is JSON, it will be converted to object. -
defaults
: Object
Default options applied to requests made from this object. The options passed into http request methods will be deep merged with default options (default options have lower priority when there are conflicts). -
Properties from axios response object (if provided):
status
,statusText
,headers
,config
,request
-
constructor(options)
- options (Object):
url
: String: Required
Url used to make this request. This will be the default url when making requests from this object.authorization
: String: Required
Authorization
header that will be the default authorization value used to make requests from this object.response
: Object: Optional
the returned response object from axios.data
: Object: Required ifresponse
is not presented
The response body. Use this option when you want to manually create Response objects instead of making API request.requestOptions
: Object: Optional
The request options used to get this response. This object is used for 2 purposes, if you're not using these features you don't need to pass in this object:- Record
params
andheaders
forrefresh()
calls - Create
defaults
property for making further requests. The created default object will be identical torequestOptions
but with some exceptions:headers
: onlyAuthorization
,X-Kloudless-As-User
, andX-Kloudless-Raw-Data
will be recorded. But all passed in headers will still be applied when callingrefresh()
url
,data
,params
: These options are discarded.
- Record
- options (Object):
-
refresh()
CallGET ${response.url}
again and update this object's properties from response. All headers will be applied as contrast to other request methods. -
- If the object was created with a request with query params, any
request made from the object will have those query params applied be default.
You can still override each query param by using
params
option
- If the object was created with a request with query params, any
request made from the object will have those query params applied be default.
You can still override each query param by using
Subclass of Response.
An object representing an object with id
property from API response.
id
: String: Resource IDtype
: String: Resource Typeapi
: String: API category of the resource
Subclass of Response. An object representing a list of resources from API response.
api
: String API category of the resource list.objects
: [Resource] A list of Resource objects under this resource list. Each resource in this list will not have properties from axios response since there is no request made for each resource object:status, statusText, headers, config, request
-
getNextPage()
Get the resources of the next page, if any.- Return Value: a Promise resolved with ResourceList object
representing next page. If the current resource list is already at the last
page, a ResourceList object with empty
objects
list will be used as resolve value. The next page will use the samepage_size
query param to make the request.
- Return Value: a Promise resolved with ResourceList object
representing next page. If the current resource list is already at the last
page, a ResourceList object with empty
-
iterate(options)
Iterate through all resources under this resource list and all resources in the following pages, if any.- options (Object):
callback
: Function: Required
A function with the first argument as the Resource object. It will be called for every resource in the list and in the following pages, if any.maxResources
: Number: Optional
Max number of resources you would like to visit. If not provided, all resources will be visited.
- Return value: A Promise resolved once all resources or max number of
resources have been iterated through.
The first argument of the resolve function is a boolean
flag
hasRemainResources
. If true, there are resources not been visited yet due to reaching maxResources limitation, you would need to calliterate
again to continue iterating through the rest of resources.
- options (Object):
-
resetIterateIndex()
Let iterate() function go back to the first resource in this resource list object, used to reset iteration progress when you'd like to do it from the beginning again.
Subclass of Response. An object representing binary files from API response.
data
:[web]
: The binary content[node]
: A readable Stream object passed from axios
-
[web]
getBlobUrl()
Create blob url fromdata
property and return blob url. Internally the blob URL is created by using URL.createObjectURL. -
[web]
removeBlobUrl()
Revoke the reference to this blob url to release the reference to the blob. Call this method when you no longer need the blob url. Internally the blob url is revoked by using URL.revokeObjectURL.- See URL.createObjectURL and URL.revokeObjectURL for more information regarding to blob url.
-
[web]
download(filename)
Prompt browser dialog to download the binary. It will callgetBlobUrl
first if the blob url is not created yet. Remember to callremoveBlobUrl
when you no longer need download url for this resource.filename
: String: Optional
Default filename when prompting download, will be"binary"
if not provided.
Subclass of global Error class. An object representing any API response that is not 2XX status, or there is no response from API, or if there is an error before making API request.
- Properties from axios error object
request
,response
,config
message
property only if axios throw an error before making a request.
message
: String- If there is a response and
message
field is presented in response body, this field is used. - If the response does not have
message
field,response.status_text
is used. - If the request is made but there is no response from API, the message will
be
"There is no response from API Server"
- If the exception was thrown before sending a request, the
message
property from axios error object is used. message || this.response.statusText
- If there is a response and
statusCode
: Number or undefined- If there is a response and
status_code
field in the response body, this field is used. - If there is a response but
status_code
field is not in response body,response.status
is used. undefined
if there is not response or the exception was thrown before making a request.
- If there is a response and
errorCode
: String or null or undefined- If there is a response and
error_code
field in the response body, this field is used. - If there is a response but
error_code
field is not in response body,null
is used. undefined
if there is not response or the exception was thrown before making a request.
- If there is a response and