-
How to send a JSON POST request using cURL?
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?
Log in to reply.