Install the json command line JSON parsing package [docs].
npm install -g json
Once that’s installed, add the following functions to your bash initialization file (i.e. .zshrc
or .bashrc
you will find them in your home directory)
post () {
curl -s -X POST -D - --header "Content-Type: application/json" --data $1 $2 | json -i
}
delete () {
curl -s -X DELETE -D - $1 | json -i
}
put () {
curl -s -X PUT -D - --header "Content-Type: application/json" --data $1 $2 | json -i
}
get () {
if [ -z "$2" ]
then
curl -s -X GET -D - $1 | json -i
else
curl -s -X GET -D - $1 | json -ic $2
fi
}
Now you’re able to query an API and get the metadata headers, and the JSON. In addition, the JSON will be formatted and human readable.
GET
I have a very simple ASP.NET Web API running on port 5000. First, I'll request all children.
get http://localhost:5000/api/child
POST
Now, I'll create a new child with a name of Miles Johansson
.
post '{"name":"Miles Johansson"}' http://localhost:5000/api/child
PUT
Then I'll update his name to Miles Champion
.
put '{"childId":21, "name":"Miles Champion", "delivered": false}' http://localhost:5000/api/child/21
DELETE
Then I delete Miles. You'll notice he's gone after I run the delete
function.
delete http://localhost:5000/api/child/21
GET filtering
I updated the data set so that two of the children have their delivered
key set to true
. I'll use the filtering capabilities of the json
library to only show those children who had their toys delivered.
get http://localhost:5000/api/child 'this.delivered===true'
Next I'll find all children that have a u
in their name.
get http://localhost:5000/api/child 'this.name.match(/u/)!==null'