How to send data in HTTP request using cURL
HTTP request consists of a request line, headers, and a body. The request line contains the HTTP method, the URL, and the HTTP version. The headers contain additional information about the request, such as the Content-Type and Accept headers. The body contains the data sent in the request.
Data can be sent in an HTTP request in several ways. The most common ways are:
-
As URL parameters in a GET request.
-
As form data in a POST request.
-
As JSON data in a POST request.
-
As multipart/form-data in a POST request.
-
As form data in a PUT request.
cURL allows you to send data in an HTTP request. cURL supports sending data in a variety of HTTP methods, such as POST, GET, PUT, and DELETE. It also supports sending data in a variety of formats, such as JSON, URL-encoded, and multipart/form-data.
Steps to send data in an HTTP request with cURL:
-
Open the terminal.
-
To send data as URL parameters in a GET request, use:
$ curl "https://www.example.com/api?param1=value1¶m2=value2"
-
To send data as form data in a POST request, use:
$ curl -d "param1=value1¶m2=value2" https://www.example.com/api
With the -d flag, cURL uses POST by default.
-
If you need to send JSON data, use the following structure:
$ curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' https://www.example.com/api
Ensure that the Content-Type header is set to application/json when sending JSON payloads.
-
To send data in a PUT request, use:
$ curl -X PUT -d "param1=value1¶m2=value2" https://www.example.com/api
-
For sending data as multipart/form-data (such as file uploads), use:
$ curl -F "file=@path_to_file" https://www.example.com/upload
The -F flag makes cURL emulate a filled-in form in which a user has pressed the submit button. This causes cURL to POST data using the Content-Type multipart/form-data.
-
To customize headers when sending data, use the -H flag followed by the header:
$ curl -H "Authorization: Bearer YOUR_TOKEN" -d "param=value" https://www.example.com/api
-
If you're dealing with an endpoint with SSL issues and wish to bypass them (mostly in development environments), use the –insecure flag:
$ curl --insecure -d "param=value" https://www.example.com/api
Using –insecure or its shorthand -k bypasses SSL certificate checks. This is risky in production environments.