Introduction to curl

This is just a barely memo about very, very basics of curl. Since curl fetches URLs and data from some endpoints, it can be used for a variety of reasons. I am using to for a very basic (and quick!) API calls tests.

If you’re on Linux, Unix or any of its clones or if you’re on Mac then you most likely have curl. If you’re on Windows, but you’re using Git for Windows (or some similar tool) then you have curl.

So, let’s jump into that basics. Be warned — you will not find here anything that you wouldn’t already knew.

Running curl

First a check-list.

  1. Very basic call: curl http://localhost/
  2. Enforcing response format: -H "Accept:application/xml"
  3. Level of response verbosity:
    • standard (download progress + response): no switch (default)
    • none; just the actual response from server: -s (silence!)
    • response + full response header: -i
    • be very verbose: -v
  4. Using non-standard REST verb (other than GET): -X POST
  5. Request parametrization:
    • sending regular parameters: -d key=val
    • sending JSON: -d '{"key":"value"}'
    • directly in URL: curl -s http://localhost/countries?sort=-code (if your endpoint supports this!)
  6. Splitting a command into a new line (clarity): \

This article assumes that you’r running examples in console and directly seeing the results. But of course you can call curl in any way you want.

Getting data

Fetching data — all objects:

curl -s http://localhost/countries
curl -s -H "Accept:application/xml" http://localhost/countries
curl -s http://localhost/countries?sort=population
curl -s http://localhost/countries?sort=-code

Fetching data — single object:

curl -s http://localhost/countries/1
curl -s http://localhost/countries/666

Setting data

This will most likely fail (or result in creating empty record):

curl -i -X POST localhost/countries

Adding new item by specifying data as JSON:

curl -i -X POST "http://localhost/countries" -d '{"code":"AQ","name":"Antarctica","population":"111"}'

Adding new object by specifying data directly:

curl -i -X POST -d code=AQ -d name=Antarctica localhost/countries

Other operations

Update object with ID = 123.

PUT /countries/123
PATCH /countries/123

Delete a record from database:

DELETE /countries/123

Calling directly from PHP

Call PHP script via RESTful API from another PHP script — an inch of integration:

<?php
$hand = curl_init();
curl_setopt($hand, CURLOPT_URL, 'http://pl.wikipedia.org/w/index.php');
curl_setopt($hand, CURLOPT_POST, 1);
curl_setopt($hand, CURLOPT_POSTFIELDS, 'title=CURL&action=edit');
curl_exec($hand);
?>

Alternatives

Postman? — https://www.postman.com/downloads/

Leave a Reply