Create Document via REST

Options

How to create a document in CS10 using REST API..? Can someone share a sample code. Thanks..

Tagged:

Comments

  • Stephen_Davis
    Options

    Hey Marimuthu,

    There are a few different ways to achieve what you are asking. The approach I took was to manually create a form data object and add the required metadata to that object. I then sent the object via an ajax request to Content Server. You will want to use an HTML5 compatible browser for the file upload portion of my code to work correctly and make sure you have jQuery accessible.

    Here is a basic HTML page that will allow you to add a document via the REST API. You will want to change some of the information in the code. You will want to change the username and password for the authenticate function to match your instance of Content Server as well as change the url for both functions to point to your instance of Content Server. Finally, make sure you add a reference to your jQuery.js file.

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Create Document REST API</title>
            <script src="<Your jQuery Location>.js"></script>
            <script type="text/javascript">
                var otcsticket = "";
                /* 
                 * This function needs to be run first to authenticate the user against Content Server.
                 */
                function authenticate() {
                    // Set up the ajax request
                    $.ajax({
                        // Authenticate is a POST
                        type: "POST",
                        url: "http://<Your CS IP>/charlie/livelink.exe/api/v1/auth",
                        data: { username: "User", password: "Password" },
                        beforeSend: function( xhr ) {
                            // Set the correct MimeType for the request.
                            xhr.overrideMimeType( "application/x-www-form-urlencoded" )
                        }
                    }).done( function( data ) {
                        if ( console && console.log ) {
                            var val = JSON.parse( data );
                            console.log( "setting otcsticket to: " + val[ "ticket" ] );
                            // Store the ticket for later use.
                            otcsticket = val[ "ticket" ];
                        }
                    });
                }
    
                /* 
                 * This function will upload the file to Content Server and print out the added document's NodeID to the console.
                 */
                function uploadFile() {
                    // Manually create a FormData object.
                    var fd = new FormData();
                    // Add the required MetaData
                    fd.append( "type", "144" );
                    fd.append( "parent_id", "2000" );
                    fd.append( "name", "NewDocument" );
                    // Grab the file we want to upload and add it to the FormData object.
                    fd.append( "file", document.getElementById( 'fileToUpload' ).files[ 0 ] );
                    console.log( "otcsticket is: " + otcsticket );
                    $.ajax({
                        // POST to /api/v1/nodes
                        type: "POST",
                        url: "http://<Your CS IP>/charlie/livelink.exe/api/v1/nodes",
                        // Our data is the FormData object we set up above.
                        data: fd,
                        contentType: false,
                        processData: false,
                        beforeSend: function( xhr ) {
                            // Add the ticket from the Autheticate function to the request header.
                            xhr.setRequestHeader( "otcsticket", otcsticket ),
                            // Update the MimeType as required.
                            xhr.overrideMimeType( "multipart/form-data" )
                        }
                        }).done(function( data ) {
                            console.log( data );
                        }).fail(function( request, statusText ) {
                            console.log( statusText );
                        });
                }
            </script>
            <meta charset="utf-8">      
        </head>
    
    <body>
        <label for="auth">Click to Authenticate</label>
        <br />
        <input id="auth" type="button" onclick="authenticate()" value="Authenticate" />
        <hr />
        <label for="fileToUpload">Select a File to Upload</label>
        <br />
        <input type="file" name="fileToUpload" id="fileToUpload" />
        <hr />
        <input type="button" onclick="uploadFile()" value="Upload" />
    </body>
    </html>
    

    There is a wide range of additional metadata that can be supplied when adding a document. I have only included what is required to add the document in my example.

    Hopefully the above code works for you without much hassle and gets you on the right track!

    Good Luck!

    -Steve.

  • Please replace http://<Your CS IP>/charlie/livelink.exe/api/v1/ with the entry point of the deployed Content Server REST API (either through the AppWorks Gateway or directly against your Content Server instance)

  • Hi Steve,

    Thanks a lot for your reply. I tried your approach and it worked as expected. I am exploring further on this part. Thanks again for the help.

  • If you use jQuery 1.5 or newer, you can simplify a little the code of Steve's excellent answer.

    The content type application/x-www-form-urlencoded is default and the data gets encoded by $.param() automatically.

    var otcsticket;
    $.ajax({
        type: "POST",
        url: "<LL CGI URL>/api/v1/auth",
        data: { username: "User", password: "Password" }
    }).done(function(data) {
      otcsticket = data.ticket;
      console.log("succeeded, otcsticket:", otcsticket);
    }).fail(function(request, statusText, statusMessage) {
      console.log("failed, message:", statusMessage);
    });
    

    Additional HTTP headers can be passed by the headers property, saving the beforeSend callback. The content type multipart/form-data is assumed if the data is an instance of the FormData. Note: FormData is available only in IE10 and newer; a workaround for IE8-9 would be beyond the scope of this topic. Other browsers have supported it since long enough.

    var fd = new FormData();
    fd.append( "type", 144 );
    fd.append( "parent_id", 2000 );
    fd.append( "name", "NewDocument" );
    fd.append( "file", document.getElementById( 'fileToUpload' ).files[ 0 ] );
    $.ajax({
      type: "POST",
      url: "<LL CGI URL>/api/v1/nodes",
      data: fd,
      contentType: false,
      processData: false,
      headers: { otcsticket: otcsticket }
    }).done(function(data) {
      console.log("succeded, id:", data.id);
    }).fail(function(request, statusText, statusMessage) {
      console.log("failed, message:", statusMessage);
    });
    

    When you create testing pages creating documents or otherwise exploring the CS REST API, you may find helpful saving the first call to api/v1/auth. If you you have the username and password, you can use Basic Authentication for every call. It's useful when you use command-like tools like curl, not to have to get the otcsticket first:

    curl -u <username>:<password> -F "type=144" -F "parent_id=2000" -F "name=NewDocument"
                                  -F "file=@<path to the file>" <LL CGI URL>/api/v1/nodes
    

    When used in the browser, you cannot use the parameters username and password of the $.ajax() function, unfortunately, because unlike in the command line tools, they'd make the XMLHttpRequest in the browser trigger the authentication request/response challenge, which the API doesn't support. The btoa() function is not available in IE8-9; you'd use a polyfill if you needed to run it there. Other browsers have supported it since long enough.

    var username = ..., password = ...,
        authorization = "Basic " + btoa(unescape(encodeURIComponent(
          username + ":" + password)));
    ...
    $.ajax({
      ...
      headers: { Authorization: authorization }
    })...;
    

    Inspect the arguments passed to the error callback. CS REST API can give you a closer explanation of the failure than the HTTP status text.

    ...fail(function(request, statusText, statusMessage) {
      var message = request.responseJSON && request.responseJSON.error || statusMessage;
      console.log("failed, message:", message);
    });
    
  • Hi

    I am trying to run the script against CS 10.5 and IE 10 combination. What version of jQuery is compatible with IE10. I have to download the jQuery.js file as the Windows 2008 server I am using does not have access to internet.
    Thank You.
    Vijhay D

  • Pick any jQuery version greater or equal to 1.6. I recommend you taking the latest stable version or a reasonably recent stable one to avoid bugs overseen or left in older versions.