It has been not even a full week building REST style interfaces for the Playmaker Studio mobile platform and I am very annoyed of all the curl guides how to access your REST API with curl. So here is my cheat sheet on this topic. Be aware that the I will update this frequently.
Common use cases
GETting data from a URL
This is a very simple use case just use:
curl will automatically use the HTTP method GET.
POSTting updates
In the REST dictionary the HTTP method POST represents the verb ‘update’. So updating data implies a POST request to an URL.
Basic
Let’s have a look at the basics, I added some (revised / half the original) debugging output by supplying the -v option.
There are some options involved:
-v added the request/response header for debugging
-X specified the request method (POST) to use.
-d added some data in the request (POST) body.
So the 'name=Niclas' was sent to the server using the request body, but curl does not display the request body using the -v option.
Using a JSON body
So this is nice, when you want to post key-value pairs to your server, but many applications (e.g. CouchDB want to post JSON objects to the server. The initial guess
does not work. That’s where the content type comes in. If you post the JSON whiteout supplying the proper content type curl and/or the server will try to use application/x-www-form-urlencoded* content type. This is the same content type your browser uses when submitting a form to a web server. Doesn’t sound bad, does it?
But it’s bad because the JSON will be ignored/dropped/whatever and the server is unable to understand the request. To solve the problem use:
So these options are involved
-X specified the request method (POST) to use.
-H added the header Content-Type: application/json to the request.
-d defined the data used for the request body ({"name":"Niclas"}).
A JSON file as body
So far so good. But if you have huge JSON requests, you don’t want to type all the JSON into the console. You may use the @ symbol in conjunction with the -d option so curl will read the request body contents from a file. This may look like this.
A nice trick is, that if you use the -d with @-. curl will read the request body from the standard input. So you can do stuff like this:
PUTting stuff
Is much like POST, so if you can POST you can PUT. One nasty little difference is, that you don’t have to supply a Content-Type HTTP header for PUT. curl does not use application/x-www-form-urlencoded as content type for PUT. Lost an hour (or so), because I did some PUT stuff before switching to POST.
Debugging
Detailed information
The key to get almost every information by supplying the -v option to curl.
But for may occasions that is simply too much, so check out the -i option.
Header information
Often it’s enough to get only the response headers for debugging. To get only these headers just use the -i option in curl.