What is the request.patch() method in Node?
Overview
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.
Syntax
request.patch(URL, DATA, CallBack());
Parameters
URL: The first parameter is theURLof the API we are making aPATCHrequest to.DATA: The second is the JSON object. ThisDATAis sent to the API to make aPATCHrequest.Callback(): This is a function which will run after the completion or failure of thePATCHmethod.
Code
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);}});
Code explanation
-
In line 1, we import the
requestmodule 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 therequest.patch()method, and is the server or site we are requesting. -
In line 8, we have
DATA, which is the second parameter for the methodrequest.patch(). This data is sent to the API. Here, we are sending JSON data with two properties:nameandmovies. -
In line 15, the
Callback()function will execute after thePATCHmethod is completed. If thePATCHrequest is successful, then thePATCHwill return with a response and body, and if it fails to make aPATCHrequest, then it will return an error. -
In line 16, we used the
ifcondition to check if ourPATCHrequest is successful or not. -
In line 17, after checking the
ifcondition, this line will execute, which means we have no error while making thePATCHrequest, and we have successfully made aPATCHrequest. We usedconsole.log(body)to print the response from the API. The body parameter contains the response JSON from API.
Output
Click the “Run” button and check the result. We have successfully completed the task to make a PATCHrequest. 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.