In this shot, we will learn how to make a post
request to an API using the Node in-built module request. We will also use and learn the request.post()
method.
The following is the syntax for the post request:
request.post(URL, DATA, CallBack());
URL
: The first parameter is the URL of the API to which we are making a post request.DATA
: Second is the JSON object; this data is sent to the API to make a POST request.Callback()
: This is a function that will run after the completion or failure of the POST method.The following is the code for the post request:
var request = require('request');request.post(//First parameter API to make post request'https://reqres.in/api/users',//Second parameter DATA which has to be sent to API{ json: {name: "paul rudd",movies: ["I Love You Man", "Role Models"]}},//Thrid parameter Callack functionfunction (error, response, body) {if (!error && response.statusCode == 201) {console.log(body);}});
In line 1, we import the request
module and create an instance.
In line 3, we use the request.post()
method.
In line 5, we have the URL
(API), which is the first parameter of the request.post()
method. This is the server or site we are requesting.
In line 8, we have Data
, which is the second parameter for the method request.post()
. This data is sent to the API. Here, we are sending _JSON data with two properties, name
and movies
.
In line 15, we have the Callback()
function, which will execute after the post
method is completed. If the post request is successful, then the post
will return with a response
and body
. If it fails to make a post request, then it will return an error
.
In line 16, we used the if
condition to check if our post
request is successful or not.
In line 17, after checking the if
condition, this line will execute, which means we have no error while making post
request and we have successfully made a post
request. We used console.log(body)
to print the response from the API. The body parameter contains the response JSON from the API.
Click the “Run” button and check the result. We have successfully completed the task to make a POST request for the output. We get a JSON object, which is returned by the API after creating. After JSON, you can see the response.statusCode
is 201
which implies created
.