DEV Community

Cover image for cURL for developers
Purna Pattela
Purna Pattela

Posted on

cURL for developers

A server is just another computer somewhere else whose job is to wait for requests and send back responses. Every time you open a website, log in to an app, or load a profile picture, your device is talking to a server in request response cycle mostly over HTTP / HTTPS.

What is cURL ?

cURL is a tool used to interact with multiple protocols from the CLI (Command Line Interface).
It supports many different protocols like http, https, dict, file, ftp, pop3, smb, etc.
In this blog lets focus only on HTTP/HTTPS Protocols using curl.

Using curl for Http/Https protocols

Generally there are 5 Methods we use in http/https protocol as a developer

  • Get : Used to fetch data from a server
  • Post : Used to send data to a server
  • Put : Used to replace the complete existing data
  • Patch : Update part of existing data
  • Delete : Used to remove data

To keep things simple we Discuss Only GET, POST (*syntax)

  • If you get get then delete was the same
  • If you get post then put and patch are the same

Get Method

Get is used to request a resource by default if we don't specify any protocol it send a get request.

Example without explicitly specifying the get method

curl https://example.com
Enter fullscreen mode Exit fullscreen mode

Example with specifying the get method

curl -X GET https://example.com
Enter fullscreen mode Exit fullscreen mode

Example for DELETE based on GET method

curl -X DELETE https://example.com/id
Enter fullscreen mode Exit fullscreen mode

Post Method

The only difference we have from the get & delete is we don't send any data from the body.

  • There is no strict rule not to send the data in the body when we use the delete method but we(developers) don't prefer

Example to send form data

curl -X POST -d "key1=value1&key2=value2" https://example.com/new
Enter fullscreen mode Exit fullscreen mode
  • -d : When we don't specify any headers by default curl send the data as application/x-www-form-urlencoded

Example to send JSON

curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1","key2":"value2"}' https://example.com/new
Enter fullscreen mode Exit fullscreen mode
  • TIP If we have a json data in a file we can send the json data as mentioned -d @path/to/jsonfile
  • In the same way we send the PUT and PATCH request

Conclusion

  • curl : Tool name to invoke from CLI
  • -X : Mention method name in capital
  • -H : To specify the headers
  • -d : To specify the data when sending the POST, PUT, PATCH requests *cURL has many other features in this blog even i did not cover 1% of its features

Top comments (0)