Curl call API , flag "‐D" vs "‐d" - unix1998/technical_notes GitHub Wiki

about the usage of curl for making API calls:

  1. -d option (data):

    • This option is used to send data to the server as part of an HTTP POST request.
    • Example: curl -X POST -d "payload" https://api.example.com/resource
    • The payload can be in various formats like JSON, XML, form data, etc. When sending JSON, it is common to use -H "Content-Type: application/json" to set the content type header.
    curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1","key2":"value2"}' https://api.example.com/resource
    
  2. -D option (dump header):

    • This option is used to save the response headers to a file.
    • Example: curl -D headers.txt https://api.example.com/resource
    • This will save the response headers to a file named headers.txt.
    curl -D headers.txt https://api.example.com/resource
    

Here's a combined example where you send a JSON payload via a POST request and save the response headers to a file:

curl -X POST -H "Content-Type: application/json" -d '{"username":"testuser","password":"password"}' -D response_headers.txt https://api.example.com/login

In this example:

  • -X POST specifies the HTTP method as POST.
  • -H "Content-Type: application/json" sets the content type to JSON.
  • -d '{"username":"testuser","password":"password"}' sends the JSON payload.
  • -D response_headers.txt saves the response headers to response_headers.txt.

These curl options are very useful for interacting with APIs, allowing you to send data to and receive information from servers efficiently.