CURL
Oct 29, 2018 11:36 · 376 words · 2 minute read
As part of my journey as a developer and decision to document my learning, I’ve been thinking of writing a short post regarding curl, here it is.
Curl is a command line tool for transferring data to and from a server. Curl stands for Client URL and was developed by a Swedish developer Daniel Stenberg @bagder.
It covers many protocols like HTTP, FTP, IMAP, POP3 & SMTP, It usually comes pre-installed in most of Linux distros and modern versions of OS X. If you’re using Windows you can either download it from here or you can use git bash
Curl has got ton of options, to see all the different options you can try the below command
curl --help
In this post, we’ll be working with jsonplaceholder, which is basically a fake online REST API that we can use for testing.
GET Request
curl https://jsonplaceholder.typicode.com/posts
if you’d like to see header information along with request’s response use flag '-i'
curl -i https://jsonplaceholder.typicode.com/posts/3
in case if you just want to get only header, use '–head' or ‘I’ flag
curl --head https://jsonplaceholder.typicode.com/posts/3
curl -I https://jsonplaceholder.typicode.com/posts/3
Often we wish to ouput the response contents into a file, for this we can use lowercase ‘o’ or '- -output' flag.
curl -o filename.txt https://jsonplaceholder.typicode.com/posts/3
POST Request
simple POST request
curl -X POST --data "title=foo&body=bar" https://jsonplaceholder.typicode.com/posts
-X : lets you change the HTTP method. -d, - -data : sends the specified data in POST request
if you want to pass your data as regular JSON.
curl -X POST \
https://jsonplaceholder.typicode.com/posts \
-H 'Content-Type: application/json' \
-d '{
"title":"foo",
"body":"bar"
}'
this returns
{
id: 101,
title: 'foo',
body: 'bar',
userId: 1
}
PUT Request
simple PUT request
curl -X PUT -d "title=foo&body=bar" https://jsonplaceholder.typicode.com/posts/1
And if you want to pass your data as regular JSON.
curl -X PUT \
https://jsonplaceholder.typicode.com/posts \
-H 'Content-Type: application/json' \
-d '{
"title":"foo",
"body":"bar"
}'
DELETE Request
curl -X DELETE https://jsonplaceholder.typicode.com/posts/1
Download
We can also download files with CURL, for that use uppercase ‘O’
curl -O https://jsonplaceholder.typicode.com/posts/3
Run in Postman
If you want to try above requests in your Postman client The below Run in Postman button imports and opens the collection of above jsonplaceholder API endpoints directly in your Postman app.
Resources
- curl tutorial - the official tutorial