cURL is a useful utility that allows you to make requests and download files & folders. It allows you to make both GET as well as POST requests. In this article, we will look at how to make POST request with cURL. This can be used to test your website/application URLs. It is also useful to test API functionality.
How to Make POST Request with cURL
It is very easy to send POST request with cURL. We will look at different use cases to help you make POST requests easily. Let us say you want to send request to URL http://localhost/api/test
Make POST request without data
Here is a simple POST request without data.
$ sudo curl -X POST http://localhost/apu/test
Please note, you need to add -X POST option to send POST request via cURL.
Also read : Bash Wait Command in Linux
POST request with data
Here is an example to send POST request with data.
$ sudo curl -X POST -d "username=test_user&password=abc" http://localhost/api/test/
You need to use -d option to send data. The data needs to be in the format of parameter=value. If you want to send multiple parameters, you need to concatenate each parameter=value with ‘&’, for example parameter1=value1¶meter2=value2…
Also read : How to Checkout Remote Branch in Git
Upload File via cURL
Here is the command to upload file via cURL command.
$ sudo curl -X POST -F file=@"path/to/file" http://localhost/api/test
You need to use to -F option to enter field values, and use file parameter to enter file path.
Multi data form
If you want to simulate a multi-data form submission, you can use -F option separately, for each data item, to enter different form data.
$ sudo curl -F name="john" -F password="abc" -F files=@"path/to/file" -F http://localhost/api/test
In the above request, we provide name, password and a file path as POST data. We have used -F option for each data item. Please remember to provide absolute file path, else cURL will look for the file in your present working directory.
Also read : How to Convert Web Page into PDF in Python
Make POST request with JSON data
Sometimes you may need to send JSON data in POST request, as is done in most web applications. In such cases, use the -H “Content-Type: application/json” option to specify the type of data you are sending. Please remember to escape double quotes while using cURL in windows.
For Windows
curl -H "Content-Type: application/json" -X POST -d {\"username\":\"test\",\"password\":\"abc\"} http://localhost/api/test
For Linux/Max
curl -H "Content-Type: application/json" -X POST -d '{"username":"test","password":"abc"}' http://localhost/api/test
That’s it. We have learnt how to send POST request using cURL. We have also looked at a few common use cases to make POST requests.
Also read : How to Run Multiple cURL Requests in Parallel
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.