News Feed Forums General Web Scraping How to send a JSON POST request using cURL?

  • How to send a JSON POST request using cURL?

    Posted by Joonatan Lukas on 12/11/2024 at 9:34 am

    Sending a JSON POST request using cURL is a common task when interacting with APIs that require JSON-formatted payloads. The -X POST option specifies the HTTP method, and the -H flag sets the headers to indicate the content type. The -d option allows you to include the JSON payload in the body of the request. This approach is ideal for tasks like submitting data, creating records, or triggering actions via an API.
    Here’s an example of sending a JSON POST request with cURL:

    curl -X POST https://api.example.com/data \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer your_api_token" \
    -d '{"key1":"value1","key2":"value2"}'
    

    Explanation:
    1.-X POST: Specifies the HTTP method as POST.
    2.-H “Content-Type: application/json”: Sets the content type to JSON.
    3.-H “Authorization: Bearer your_api_token”: Adds an authentication token in the request header (if required).
    4.-d ‘{“key1″:”value1″,”key2″:”value2”}’: Defines the JSON payload to send in the request body.
    You can also save the JSON payload in a file and pass it to cURL:

    curl -X POST https://api.example.com/data \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer your_api_token" \
    -d @data.json
    

    This approach is particularly useful when working with large or reusable JSON data files. How do you handle responses and errors when making POST requests with cURL?

    Prashant Sanjiv replied 1 week, 4 days ago 3 Members · 2 Replies
  • 2 Replies
  • Shena Brigid

    Member
    12/11/2024 at 11:57 am

    When debugging, I use the -v flag for verbose output to see detailed request and response information. This helps identify missing headers or incorrect payloads.

  • Prashant Sanjiv

    Member
    12/12/2024 at 7:19 am

    Using the –retry option in cURL helps manage temporary network failures by retrying the request automatically after a delay.

Log in to reply.