Mauritz Hansen
Mauritz Hansen

Reputation: 4774

How to test web service using command line curl

I am building a web service for a web application, and I would like a simple tool to test this as I am developing. I have tried some firefox plug-ins (Poster, 'REST Client'), and even though these work fine I have been unable to upload files with them.

Also, I would rather have a command-line tool that I can use to easily write a set of integration tests for this web service and that I can send to consumers of this web service as an example.

I know that curl can work for this but would like a few examples, especially around authentication (using HTTP Basic) and file uploads.

Upvotes: 28

Views: 147881

Answers (4)

Michael
Michael

Reputation: 1

I have been using hurl for a while now. It allows to write simple test cases by defining HTTP requests (including basic authentication and request bodies) and asserting specific/expected properties of the HTTP response. It can even capture values from the response and feed them into subsequent (chained) requests. See https://hurl.dev/ for details.

Upvotes: 0

Mauritz Hansen
Mauritz Hansen

Reputation: 4774

Answering my own question.

curl -X GET --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X DELETE --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
     -d 'param2_name=param2_value' https://www.example.com/mobile/resource

POSTing a file and additional parameter

curl -X POST -F 'param_name=@/filepath/filename' \
     -F 'extra_param_name=extra_param_value' --basic --user username:password \
     https://www.example.com/mobile/resource

Upvotes: 26

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:

$ curl https://api.twitter.com/1/help/configuration.xml  | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool

Tested on Ubuntu 11.0.4/11.10.

Another issue is the desired content type. Twitter uses .xml/.json extension, but more idiomatic REST would require Accept header:

$ curl -H "Accept: application/json"

Upvotes: 18

alessioalex
alessioalex

Reputation: 63663

From the documentation on http://curl.haxx.se/docs/httpscripting.html :

HTTP Authentication

curl --user name:password http://www.example.com 

Put a file to a HTTP server with curl:

curl --upload-file uploadfile http://www.example.com/receive.cgi

Send post data with curl:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi

Upvotes: 4

Related Questions