Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js
communitycreator

What is a Node PUT request?

Ayush Trivedi

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 PUT and POST method can create and update resources.

  • But the PUT request is used to update data in database, whereas POST requests 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 the PUT request to.
  • DATA: The second is the JSON object. This data is sent to the API to make a PUT request.
  • Callback(): This is a function which will run after the completion or failure of the PUT method.

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 function  
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
            console.log(response.statusCode);
        }
    }
);

Code explanation

  • In line 1, we import the request module 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 the request.put() method. This is the server or site we are requesting.

  • In line 8, data is the second parameter for the method request.put(). This data is sent to the API. Here, we are sending JSON data with two properties: name and job.

  • In line 15, we have the Callback() function, which will execute after the PUT method is completed. If the PUT request is successful, then the PUT will return with a response and body, and if it fails to make PUT request, then it will return an error.

  • In line 16, we used the if condition to check if our PUT 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 PUT request and we have successfully made a PUT request. We have used console.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.

RELATED TAGS

node.js
communitycreator
RELATED COURSES

View all Courses

Keep Exploring