What is a Node PUT request?
Overview
In this shot, we will learn how to make a PUT request to an API using a Node in-built module request.
-
Both the
PUTandPOSTmethod can create and update resources. -
But the
PUTrequest is used to update data in database, whereasPOSTrequests create the data.
In this shot, we will learn how to use the request.put() method.
Syntax
request.put(URL, Data, CallBack());
Parameters
URL: The first parameter is the URL of the API we are making thePUTrequest to.DATA: The second is the JSON object. This data is sent to the API to make aPUTrequest.Callback(): This is a function which will run after the completion or failure of thePUTmethod.
Code
var request = require('request');request.put(//First parameter API to make post request'https://reqres.in/api/users/2',//Second parameter Data which has to be sent to API{ json: {"name": "morpheus","job": "zion resident"}},//Thrid parameter Callack 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.put()method. -
In line 5, we have the
URL(API), which is the first parameter of therequest.put()method. This is the server or site we are requesting. -
In line 8,
datais the second parameter for the methodrequest.put(). This data is sent to the API. Here, we are sending JSON data with two properties:nameandjob. -
In line 15, we have the
Callback()function, which will execute after thePUTmethod is completed. If thePUTrequest is successful, then thePUTwill return with a response and body, and if it fails to makePUTrequest, then it will return an error. -
In line 16, we used the
ifcondition to check if ourPUTrequest is successful or not. -
In line 17, after checking the
ifcondition, this line will execute, which means we have no error while making thePUTrequest and we have successfully made aPUTrequest. We have usedconsole.log(body)to print the response from the API, where the body parameter contains the response JSON from the API.
Output
Click the Run button and check the result. We have successfully completed the task to make a PUT request. The output we get is a JSON object which is returned by the API after creating. After JSON, you can see response.statusCode is 200, which implies it is updated.