Curl is a command line utility that was created in 1998 for transferring data using URLs. Fundamentally, curl
allows users to create network requests to a server by specifying a location in the form of a URL and adding optional data.
curl
(short for “Client URL”) is powered by libcurl – a portable client-side URL transfer library written in C.
Why use the curl command?
Common use cases for curl
include:
- It can download and upload files
- It has great error logging
- It allows for quick endpoint testing
- It provides granular details which aides debugging
- It is portable and works with most operating systems
- It is an actively managed open-source tool that is battled tested with a large user base
Base curl
command usage
The basic syntax for a curl
command is:
|
|
HTTP Requests using curl
Curl provides native support for all HTTP requests methods: GET
, POST
, PUT
, PATCH
, DELETE
, etc.
For all the following examples, the JSONPlaceholder API will be used.
Make a GET
request
|
|
OR
|
|
NOTE: The -X
flag is a shorthand for --request
. It’s not required because the default value is GET
.
Output:
|
|
In addition, an optional Accept
header may be used:
|
|
Make a POST
request
|
|
In the example above, a new post titled foo
with a body of test
is created.
The default Content-Type
of the request is: application/x-www-form-urlencoded
If a JSON
payload is required, then the Content-Type
header can be explicitly included:
|
|
Alternatively, a file may be specified (post.json
):
|
|
|
|
Output:
|
|
Make a PUT
request
Similarly to POST
, a PUT
can use all the same options:
|
|
In the example above, post 1 is re-titled to foo
and given a new body of test
.
The default Content-Type
of the request is: application/x-www-form-urlencoded
If a JSON
payload is required, then the Content-Type
header can be explicitly included:
|
|
Alternatively, a file may be specified (post.json
):
|
|
|
|
Output:
|
|
Make a PATCH
request
Similarly to POST
and PUT
, a PATCH
can use all the same options:
|
|
In the example above, post 1 is re-titled to foo2
.
The default Content-Type
of the request is: application/x-www-form-urlencoded
If a JSON
payload is required, then the Content-Type
header can be explicitly included:
|
|
Alternatively, a file may be specified (post.json
):
|
|
|
|
Output:
|
|
Make a DELETE
request
|
|
Output:
|
|
Conclusion
curl
is a powerful and versatile command line utility that offers a wide range of supporting features: multiple protocols, multiple options, data types, etc. HTTP requests are simple and reliable.