What is cURL
?
cURL
is a
standard, popular tool for performing HTTP requests on the
command line. It comes pre-installed on many systems. Being
able to use cURL effectively is an important skill to have as
a web developer. Curl is often the first tool many people turn
to for debugging or automating HTTP requests.
In order to use
curl
you will need some understanding of the HTTP protocol. If you're unfamiliar with HTTP, checkout A Beginner's Guide to HTTP and REST and The HttpWatch Guide to HTTP
A GET
Request
If you have curl
installed on your system, you
can make a basic request like this:
curl http://google.com
A POST
Request
You can also use cURL to mimic submitting a form by using a
POST
request.
Here is how you can submit a POST
request to
GraphQL hub:
curl -H 'Content-Type:application/graphql' -XPOST https://www.graphqlhub.com/graphql?pretty=true -d '{ hn { topStories(limit: 2) { title url } } }'
Notice that there are three options here, passed as "flags":
-
-H
- states that we want to pass a header. In this case, we're passing ht HTTP headerContent-Type
asapplication/graphql
-
-XPOST
- states that we want to send aPOST
request -
-d
- states that the string that follows is thePOST
body. In this case, it is a GraphQL query that fetches the top 2 posts from Hacker News.
Chrome "Copy as cURL"
Chrome has a powerful feature that lets you copy any HTTP operation a cURL request. To do this:
- Open up the Chrome Developer Tools
- Click on the "Network" Tab
- Navigate with your browser / perform the operation you want to copy
- Locate your HTTP request in the list of requests
- Right click the request and pick "Copy as cURL"
- Paste your request into your shell
When you paste the command, you'll notice that it has a lot of "noise". The browser sends quite a lot of headers! Not all of them are always necessary for your request to succeed, but it's a good starting point. This can be especially helpful when you have authentication cookies stored in your browser and you need to debug a protected request.
curl 'https://www.newline.co/fullstack-react/assets/vendor/functions.js' -H 'if-none-match: W/"5dd95509e78d11579fc427e9f41889d6"' -H 'accept-encoding: gzip, deflate, sdch' -H 'accept-language: en-US,en;q=0.8' -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36' -H 'accept: */*' -H 'cache-control: max-age=0' -H 'authority: www.fullstackreact.com' -H 'cookie: __cfduid=d309889bd8e027d878c2e16e0176e764d1463427161; _ga=GA1.2.135748265.1463427163; _gat=1' -H 'if-modified-since: Tue, 15 Mar 2016 03:37:56 GMT' -H 'referer: https://newline.co/fullstack-react/' --compressed
Though not technically identical, the essential, trimmed down version of this request could be:
curl 'https://www.newline.co/fullstack-react/assets/vendor/functions.js'
More Resources
If you learn more about cURL, checkout: