Posts Tagged ‘JavaScript’

Command Line Script for Calling REST Based Web Services

Tuesday, July 13th, 2010

I have been working with REST based web services recently and whilst reading the very useful and interesting article A Guide to Designing and Building RESTful Web Services with WCF 3.5 hosted on the Microsoft web site. Came across this useful little JavaScript script that can be called from the command line to invoke your  RESTful web services.

The code is shown below.

if (WScript.Arguments.length < 2)

{

   WScript.echo("Client HTTP Request Utility\n");

   WScript.echo("usage: httprequest method uri [options]");

   WScript.echo("  -f filename");

   WScript.echo("  -h headerName headerValue");

   WScript.Quit(1);

}

var method = WScript.Arguments.Item(0);

var uri = WScript.Arguments.Item(1);

var req = new ActiveXObject("MSXML2.XMLHTTP");

var filename = null;

req.Open(method, uri, false);


WScript.echo("********* Request ********* ");

WScript.echo(method + " " + uri + " HTTP/1.1");

for (i=2; i < WScript.Arguments.length; i++)

{

    var option = WScript.Arguments.Item(i);

    if (option == "-f")

        filename = WScript.Arguments.Item(i+1);

    if (option == "-h")

    {

        WScript.echo(WScript.Arguments.Item(i+1) + ": " +

            WScript.Arguments.Item(i+2));

        req.setRequestHeader(WScript.Arguments.Item(i+1),

            WScript.Arguments.Item(i+2));

    }

}

try

{

       if (filename != null)

       {


          var fso = new ActiveXObject("Scripting.FileSystemObject");

          var file = fso.OpenTextFile(filename, 1, false);

          var fileContents = file.ReadAll();

          file.Close();

          WScript.echo(fileContents);

          req.Send(fileContents);

          printResponse(req);

       }

       else

       {

          req.send();

          printResponse(req);

       }

}

catch(e)

{


   WScript.echo("******* Response ********* ");

   WScript.echo(e.message);

}

function printResponse(req)

{


   WScript.echo("******* Response ********* ");

   WScript.echo("HTTP/1.1" + " " + req.status + " " + req.statusText);

   var headers = req.getAllResponseHeaders();

   WScript.echo(headers);

   WScript.echo(req.responseText);

}

To perform a GET simply type from the command line:

HttpUtility.js get http://localhost:1189/Service.svc/

where HttpUtility.js is the file name containing the JavaScript code shown above and the URL of our REST service.

To perform a POST:

HttpUtility.js post http://localhost:1189/Service.svc/ –f message.xml -h Content-Type application/xml

where the –f argument specifies the filename with the message contents and the –h argument indicates the header name and header value.

The source code can be downloaded from here.