In this shot, we will learn how to make a PATCH
request to an API using a Node in-built module request.
PATCH
and PUT
both are used to update data in the resource. But PATCH
is not idempotent like PUT
.
In this shot, we will learn about the request.patch()
method.
request.patch(URL, DATA, CallBack());
URL
: The first parameter is the URL
of the API we are making a PATCH
request to.DATA
: The second is the JSON object. This DATA
is sent to the API to make a PATCH
request.Callback()
: This is a function which will run after the completion or failure of the PATCH
method.var request = require('request');request.patch(//First parameter API to make post request'https://reqres.in/api/users',//The second parameter, DATA which has to be sent to API{ json: {name: "paul rudd",movies: ["I Love You Man", "Role Models"]}},//The third parameter is a Callback functionfunction (error, response, body) {if (!error && response.statusCode == 200) {console.log(body);console.log(response.statusCode);}});
In line 1, we import the request
module and create an instance.
In line 3, we use the request.patch()
method.
In line 5, we have URL
(API), which is the first parameter of the request.patch()
method, and is the server or site we are requesting.
In line 8, we have DATA
, which is the second parameter for the method request.patch()
. This data is sent to the API. Here, we are sending JSON data with two properties: name
and movies
.
In line 15, the Callback()
function will execute after the PATCH
method is completed. If the PATCH
request is successful, then the PATCH
will return with a response and body, and if it fails to make a PATCH
request, then it will return an error.
In line 16, we used the if
condition to check if our PATCH
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 the PATCH
request, and we have successfully made a PATCH
request. We used console.log(body)
to print the response from the API. The body parameter contains the response JSON from API.
Click the “Run” button and check the result. We have successfully completed the task to make a PATCH
request. The output we get is a JSON object which is returned by the API
after creating. After JSON, you can see the response.statusCode
is 200, which implies it is updated.