Open In App

Explain Different Types of HTTP Request

Last Updated : 03 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Hypertext Transfer Protocol (HTTP) defines a variety of request methods to describe what action is to be done on a certain resource. The most often used HTTP request methods are GET, POST, PUT, PATCH, and DELETE.

Let’s understand the use cases of HTTP requests:

  • GET: A GET request reads or retrieves data from a web server. If the data is correctly collected from the server, the HTTP status code is 200 (OK).
  • POST: A POST request is used to transmit data to the server. It produces an HTTP status code of 201 on successful creation.
  • PUT: A PUT request is used to alter server data. It replaces all of the content at a specific position with data from the body payload. It will generate one if there are no resources that match the request.
  • PATCH: A PATCH request is identical to a PUT request, with the exception that it alters a portion of the data.
  • DELETE: A DELETE request is used to delete data from a specific place on the server.

Let’s go through each of these request methods in detail now. We’ve put up a simple application using a NodeJS server and a MongoDB database. The NodeJS server will process all requests and respond appropriately.

Project Setup:

Step 1: Create a folder named API and run the following command to launch a NodeJS application.

npm init -y

Step 2: Install the necessary npm packages using the following command.

npm install express body-parser mongoose nodemon

Step 3: Create a file called index.js in your project directory.

Project Structure: This is how our project directory should now appear.

q

Step 4: Require and set up the express app, so that it starts listening to the requests. Our server is set on Port 3000.

Javascript




const express = require("express");
const bodyParser = require("body-parser");
  
const app = express();
  
app.use(express.json());
app.use(
  bodyParser.urlencoded({
    extended: true
  })
);
  
app.listen(3000, () => {
  console.log("Server started on port 3000");
});


Step 5: Include the following script in the package.json file. This implies that we can use npm start to start our server, and it will use the Nodemon package that we previously installed.

package.json




"scripts": {
    "start": "nodemon index.js"
},


Step 6: Type npm start in the terminal to start the server.

 

Step 7: Require the mongoose package and connect to the MongoDB database. If you are working on a project locally, MongoDB server URL is likely this mongodb://localhost:27017/database name. 27017 is the default port.

Javascript




const mongoose = require("mongoose");
mongoose
    useNewUrlParser: true,
  })
  .then(() => {
    console.log("Database connected");
  })
  .catch((err) => {
    console.log("Connection failed");
  })


Step 8: Restart the server to check, whether the database is successfully connected or not.

 

How to make a POST request?

Step 1: Create a Model to outline the structure of our database. We have a schema here that describes the structure of our database. It has a title and content property. Both fields include types and are necessary.

Javascript




const articleSchema = {
  title: {
    type: String,
    required: true,
  },
  content: {
    type: String,
    required: true,
  },
};
  
const Article = mongoose.model(
  "Article", articleSchema);


Step 2: Create an endpoint for the post request and add the data body to the post using the model we just created. The title and content are accepting the title and content from the request body. This information is obtained via a client app such as Postman or Insomnia.

Making and Handling the post request:

Javascript




app.post("/articles", (req, res) => {
  const newArticle = new Article({
    title: req.body.title,
    content: req.body.content,
  });
  
  newArticle.save((err) => {
    if (!err) {
      res.send("Successfully added a new article.");
    } else {
      res.send(err);
    }
  });
});


Step 3: Open up the Postman, add the data in the body and Click send.

 

Step 4: Check the database and you will see the record you just created.

 

Making and Handling the get request:

Step 1: To fetch the data from the database, we have to use Model.find() method from Mongoose.

Javascript




app.get("/getAllarticles", async (req, res) => {
  try {
    const article = await Article.find({});
    if (article.length != 0) {
      res.send(article);
    } else {
      res.send("No article found");
    }
  } catch (error) {
    console.log(error);
  }
});


Step 2: Send the GET request to the server with the help of Postman.

 

Making and Handling patch requests:

Step 1: We will use the findOneAndUpdate() method from mongoose to find a document by its title and update it. 

Javascript




app.patch("/articles/:articleTitle", (req, res) => {
  Article.findOneAndUpdate(
    { title: req.params.articleTitle },
    { $set: req.body },
    function (err) {
      if (!err) {
        res.send("Successfully updated article.");
      } else {
        res.send(err);
      }
    }
  );
});


Step 2: Let’s test it out now. Mention the title of the article which you want to update and add the updated content in the body. Finally, click Send.

 

Step 3: To check whether the particular article is updated or not send a GET request to the server, and you will see that the content of a particular article is changed. 

 

Making and Handling delete requests:

Step 1: To delete a particular article we will deleteOne() method from mongoose. The deleteOne() method will first find an article by its title and then delete it as we did in the case of a PATCH request.

Javascript




app.delete("/articles/:articleTitle", (req, res) => {
  Article.deleteOne({ title: req.params.articleTitle }, function (err) {
    if (!err) {
      res.send("Successfully deleted the corresponding article.");
    } else {
      res.send(err);
    }
  });
});


Step 2: Mention the title of the article which you want to delete and send the request to the server.

 

Step 3: To check whether the particular article is deleted or not send a GET request to the server, and you will see that the particular article is removed from the database.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads