Curl is a popular command line tool often used for making HTTP requests. Curl supports a wide variety of other protocols, but, as a Node.js developer, you’ll most likely use it to make HTTP requests to RESTful APIs.
Unfortunately, the curl docs list 383 supported command-line flags, which makes it difficult to find what you’re looking for. In this article, I’ll list out the patterns that I find myself using most often with curl, using the excellent httpbin.org service as an example.
First, double-check that you have curl installed by running curl --version
.
$ curl --version
curl 7.58.0 (x86_64-pc-linux-gnu) libcurl/7.58.0 OpenSSL/1.1.1 zlib/1.2.11 libidn2/2.0.4 libpsl/0.19.1 (+libidn2/2.0.4) nghttp2/1.30.0 librtmp/2.3
Release-Date: 2018-01-24
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets HTTPS-proxy PSL
To make an HTTP GET request, you just need to run curl <url>
. For example, to make an HTTP GET request to https://httpbin.org/get?answer=42
, you can run curl https://httpbin.org/get?answer=42
.
$ curl https://httpbin.org/get?answer=42
{
"args": {
"answer": "42"
},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"User-Agent": "curl/7.58.0",
"X-Amzn-Trace-Id": "Root=1-5ee8d737-b39c6a466892725bbb52b916"
},
"origin": "69.84.111.39",
"url": "https://httpbin.org/get?answer=42"
}
$
When the HTTP request succeeds, curl prints out the HTTP response body. To make curl print the entire response, including response headers, use the -i
flag.
$ curl -i https://httpbin.org/get?answer=42
HTTP/2 200
date: Tue, 16 Jun 2020 14:30:57 GMT
content-type: application/json
content-length: 801
server: istio-envoy
access-control-allow-origin: *
access-control-allow-credentials: true
x-envoy-upstream-service-time: 2
{
"args": {
"answer": "42"
},
"headers": {
"Accept": "*/*",
"Content-Length": "0",
"Host": "httpbin.org",
"User-Agent": "curl/7.58.0",
"X-Amzn-Trace-Id": "Root=1-5ee8d7a1-cb3954c09299eb9e0dff70a6",
"X-B3-Parentspanid": "dffc55451e64b5fc",
"X-B3-Sampled": "0",
"X-B3-Spanid": "8e233a863fb18b6c",
"X-B3-Traceid": "45bd12a9067fb5c0dffc55451e64b5fc",
"X-Envoy-External-Address": "10.100.91.201",
"X-Forwarded-Client-Cert": "By=spiffe://cluster.local/ns/httpbin-istio/sa/httpbin;Hash=c1ff14671b3e24ee794f9a486570abf8ccc9d622846611d3f91a322db4d480cd;Subject=\"\";URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account"
},
"origin": "69.84.111.39,10.100.91.201",
"url": "http://httpbin.org/get?answer=42"
}
The above output is a raw HTTP response. The response headers are the lines from date:
to x-envoy-upstream-service-time:
.
#javascript #node #programming #developer