Google

Jun 10, 2013

Testing RESTful web services with the cURL command line tool



The modern web application development is full of RESTful web services, and it very handy to know a few tools to test the RESTful web services.



Q. What is a cURL command line tool?
A. RESTful web applications are widely used and developed in many languages including Java, and cURL is a command line tool to quickly test RESTful web service functionality. cURL is a Unix operating system based tool. Here are some examples,

Note that this is a HEAD request, and -X is used to define the HTTP method or verb like HEAD, GET, POST, PUT, etc. The following example shows testing a health check URL to see if the RESTful web service is up. "-i" is used to show the response headers. "-H" is used to pass the request headers with the request.

curl  -i -H Content-Type:application/json -X HEAD "http://localhost:8080/my-server/myapp/healthcheck"

Response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Length: 0
Date: Wed, 27 Mar 2013 23:54:38 GMT

Here is an example of a GET request:

curl -i -X GET -H Accept:application/json 'http://localhost:8080/my-server/myapp/person?first_name=john&last_nane=smith'

Response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: no-cache
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 21 Mar 2013 01:39:22 GMT

{"id":100,"first-name":"John", "last-name:Smith", "title":"Mr."}


Note: The resource uri needs to be quoted if you pass in multiple query parameters separated by ‘&’. If you have spaces in the query values, you should encode them i.e. either use the ‘+’ symbol or %20 instead of the space. Also, For GET requests, the -X GET is optional.


Here is an example of a POST request: "-d" is used for the data to be posted

curl -i -H "Accept: application/json" -X POST -d "firstName=james" http://localhost:8080/my-server/myapp/persons/person

The PUT request is done very similar to a POST request as shown above, but with -X PUT. A POST request is used to create a new person record and a PUT request is made to edit an existing person record as shown below.

curl -i -H "Accept: application/json" -X PUT -d "firstName=john" http://localhost:8080/my-server/myapp/persons/person/100


Here is an example of a DELETE request:

curl -i -H "Accept: application/json" -X DELETE http://localhost:8080/my-server/myapp/persons/person/100


There are other good tools to test RESTful web services like the Poster plugin from Firefox Add-on. Another great tool that I have blogged about is the RESTClient stand alone jar.  These two are great GUI tools if you do not want to get down and dirty with cURL or if you are testing from Windows you could install Cygwin and then install and use cURL.

Labels: , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home