Thursday, May 12, 2016

Using curl command line

Up until now, I've generally used fiddler's composer to test web services. However, it's a bit of a heavyweight, and especially if I'm writing web services in linux, it's more work to get fiddler up and running than to type out a curl command on a terminal. So I learned just enough curl to test out web services.

In the most elemental form, you can do
curl [url]
For example, if you hit as below, then you get an HTTP 301 - Moved (which if you did from a browser, the browser will automatically interpret the 301 response and take you to the new destination).

Sending post data is trickier. First off, you need to override the default method of GET. You also need to specify the data to send, and you need to specify the content type of that data.
  • Override the GET method:
    • This is done by specifying the -X option followed by the method to use
  •  The data to be sent:
    • This specified by the -d option (or --data in full) followed by the data in quotes.
  • The content type:
    • This is specified by using the Content-Type HTTP header. 
    • Headers are added using the -H option followed by the header specification in quotes.
So for example:
curl -X POST -H "Content-Type: text/plain" -d "Hello world"
Will post the string "Hello world" as plain text to the web service.

You can also use PUT method etc and modify the command appropriately.

But what if the data you want to post isn't a small string, but the contents of a file rather? In that case, you specify the filename prefixed with @ and in quotes as argument to the -d option
curl -X POST -H "Content-Type: text/plain" -d "@path/filename"

No comments: