Getting an Object Body via the REST API

In this example, we first call an external server via the REST API and then handle the object body.

You can call any external server using jQuery in your server code. There is no limitation in accessing domains while we call Kii Cloud in this example.

The current server extension does not support Blob and FileReader that are needed to handle object bodies, so you need to use the REST API to handle them in your server code.

Here is the server code example. In the sample code, we get the object body of a KiiObject in the application scope by specifying it with the bucketName and objectId parameters. We do not manipulate the obtained object body in this example.

function parse_body(params, context, done) {
  // Compose the URL of the published object body and get the administrator's token.
  var appId = context.getAppID();
  var appKey = context.getAppKey();
  var adminToken = context.getAppAdminContext()._getToken();
  var targetUrl = Kii.getBaseURL() + "/apps/" + appId + "/buckets/" + params.bucketName + "/objects/" + params.objectId + "/body";

  $.ajax({
    // Get the object body.
    url: targetUrl,
    type: "GET",
    headers: {
      "Accept": "*/*",
      "Authorization": "Bearer " + adminToken
    },
    success: function(body) {
      // Process the object body.
      done("OK");
    },
    error: function(msg) {
      done("NG:" + JSON.stringify(msg));
    }
  });
}

Hints

  • The HTTP GET method is used in this example. You can also change the type in $.ajax to another method. Make sure to use the upper letter for the method name. For example, the method name "Post" does not work.

  • When passing a JSON object in the REST request, use the stringfy() method when specifying the data in $.ajax (i.e., specifying the HTTP BODY), like JSON.stringify({"param" : "value"}).

  • Be careful with the total size of parameters to be passed to your server code in writing a process to upload client data based on this download sample. The maximum size is 100 KB for the total of parameters and approximately 50 bytes of metadata to invoke the server code.

You cannot execute server code by manually executing another server code. If you attempt to do so, you will get an HTTP 409 response with the "OPERATION_NOT_ALLOWED" error.

  • If Basic authentication is required, for example, for communication with an external server, update the line to output the Authorization header as below. It is assumed that the server code caller encodes the username and password for Basic authentication to Base64 and passes the encoded string as the base64token parameter.

    "Authorization": "Basic " + params.base64token