Sending JSON data using ‘–json’ option
There is another method is also available in cURL utility for sending JSON. This option available in 7.82.0 version. This version include in option in cURL ‘–json’.
Example: Sending POST request using ‘–json’.
curl -X POST -H "Content-Type: application/json" --json {"username":"admin","password":"admin"}' http://localhost:5050/login
Output:
"User login Successfully"
How to Post JSON Data using Curl ?
One can send the post data using curl (Client for URLs), a command line tool, and a library for transferring data with URLs. It supports various types of protocols. Most of the use cases of the curl command are posting JSON data to a server endpoint.
CURL
cURL stands for ( Client for URLs) and is a command line tool and library for transferring data with URLs. It supports many protocols, including HTTP, HTTPS, FTP, FTPS, SCP, SFTP, LDAP, and TFTP. Daniel Stenberg developed it, cURL is open source and widely used in development and system administration tasks. It is preinstalled in Linux-based distros.
Syntax:
curl [options] [URL]
Options in the CURL tool:
- -X: This option specifies the HTTP method (GET, POST,PUT,DELETE etc).
- -H: This option adds the customer Headers to the request.
- -d: This option sends data in the request body using the POST requests.
- -o: This option write output into a file.
- -O: Downloads the file and uses the remote file name.
- -L: It follows redirects.
- -u: This option provides a username and password for authentication.
JSON
JSON , which stands for JavaScript Object Notatino, is a lightweight data interchange format. It is used for sending the data over the Internet. It is easy to read and write for humans. JSON is often used to transmit data between a server and a web application as an alternative to XML(eXtensible Markup Language).
Example: To demonstrate the simple JSON data.
{
"username": "example_user",
"password": "P@ssw0rd123"
}
Table of Content
- Using the “-d” or “–data” option in CURL Command
- Sending JSON data from a file
- Sending JSON data using ‘–json’ option
Server Code
In this examples, I created a simple server using the Node.js with Express framework. In this code, there is login page where the server check the user password is correct or not. If the user is not correct. Then, It will throw an error otherwise. User will login Successfully.
Step 1: Installing the dependencies
npm install express
Step 2: Installing the nodemon package
npm install nodemon
Step 3: Running the Server using the following command
npm start
Package.json
const express = require('express');
const app = express();
app.use(express.json());
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === password) {
res.send("User login Successfully")
.status(200);
}
else {
res
.send("User not Logging ")
.status(401);
}
})
app.listen(5050, () => {
console.log("Server is Running");
})