curl
is a useful tool used to create HTTP, HTTPS, FTP, … and similar protocol requests from the command line. This provides us the ability to simulate web browser behavior or similar application logic without a GUI. In this tutorial, we will look at different use cases for curl POST and JSON. For more information about curl can be get from the following tutorial.
Linux curl Command Tutorial With Examples
Simple POST Example
We will start with a simple POST example. We will provide some fields in the POST with the –data option. In this example, we will provide username=ismail&password=poftut
as POST data. Use double escapes to delimit data we wan to post.
$ curl --data "username=ismail&password=poftut" poftut.com
Read POST Data From File
What if we have more data that is not suitable to write one by one of specifying from command line. Or we may need to provide data as a file. We can use the same --data
option but we have to provide the file name with @
prefix. In this example, we will provide a file named mydata.txt
as POST data.
$ curl --data "@mydata" poftut.com
Set Content Type
Up to now, we have used the default Content-type. Some times we may need to specify the content type explicitly. We will use -H option which is used to specify HTTP header where we will provide Content-Type header. In this example, we will set PDF ad content type.
$ curl --data "@mydata" -H "Content-Type:application/pdf" poftut.com
Post JSON Data
JSON is a popular data format used recently in high volumes. JSON is an easily readable structured and light data format. We can send POST requests to the server by providing JSON Data. We just need to provide the Content-Type
as application/json
and put JSON data accordingly. In this example, we will send count JSON data.
$ curl --data "{'count':'5'}" -H "Content-Type:application/json" poftut.com
Post JSON Multiple Key=Value Like Username and Password
One of the most popular use cases for JSON curl is sending username and password data to the server. We have to specify both keys and values accordingly like below.
$ curl --data "{'username':'ismail','password':'pof'}" -H "Content-Type:application/json" poftut.com
Read JSON POST Data From File
We have read normal POST data from a file. But we can also read JSON POST data from the file where we just need to specify file name like below.
$ curl --data "@myjsondata" -H "Content-Type:application/json" poftut.com