Testing a JSON API with Curl

Frederic Cambus September 27, 2014 [Command Line]

I've been working a lot on JSON APIs during the past few years, and even more intensively lately. If testing GET requests is straightforward, for POST requests I often had to look at Curl documentation again for exact options names and parameter syntax for sending the desired HTTP headers.

So I decided to post some quick notes on doing unauthenticated POST requests, in order to have a quickly accessible reference.

Here is a list of some relevant Curl options:

-d, --data DATA     HTTP POST data (H)
-X, --request COMMAND  Specify request command to use
-H, --header LINE   Custom header to pass to server (H)

Doing an empty POST request

curl --request POST http://127.0.0.1:8080/api/store

Posting JSON data

curl --request POST --data "{ \"ip\": \"46.19.37.108\", \"country_code\": \"NL\", \"country_code3\": \"NLD\", \"country\": \"Netherlands\", \"continent_code\": \"EU\", \"latitude\": 52.5, \"longitude\": 5.75, \"dma_code\": \"0\", \"area_code\": \"0\", \"asn\": \"AS196752\", \"isp\": \"Tilaa V.O.F.\", \"timezone\":\"Europe/Amsterdam\" }" http://127.0.0.1:8080/api/store --header "Content-Type: application/json"

Posting JSON data from a file

curl --request POST --data @filename http://127.0.0.1:8080/api/store --header "Content-Type: application/json"

This is particularly handy when working with large JSON objects.

Lastly, for a fully client-side JSON validator and formatter, check JSON.fr.