cover-img

Demystifying REST API: A Beginner's Guide

4 July, 2023

4

4

2

Every website we visit often has its own API, including popular platforms like Twitter. Let's take Twitter as an example. When we search for a user, such as Saurav_Pant_, Twitter utilizes its REST API to handle our request. The API acts as a bridge between the website and its database, processing our search query and fetching the relevant user information. The response from the API is usually in a format called JSON, which is a structured way of organizing data. On the client side, which can be a web browser or an app, the JSON data is processed and presented in a user-friendly manner, such as showing the user's profile information or their recent tweets.

Now, if you're interested in creating your own REST API, here are some steps to follow:

  1. Installing Node.js:-

To get started, we'll need to install Node.js, which is a powerful JavaScript runtime. You can download it from the official website at:

https://nodejs.org/en

  1. Initialize the Project 😀

Once we have Node.js installed, let's create a new directory for our REST API project. Open the terminal or command prompt and run the following commands:

mkdir Rest_API
cd Rest_API
npm init -y


These commands will create a new folder called Rest_API and initialize a new Node.js project inside it.

  1. Install Express:-

Express is a popular framework for Node.js that simplifies the process of building APIs. It provides a set of tools and functions that make writing code easier and more efficient. To install Express, run the following command in the terminal:

npm install express
  1. Initializing the App:-
const express = require("express");
const app = express();

app.listen(5000, () => {
console.log("Server is running on port 5000");
});

In this code, we import the express module and create an instance of the Express application by calling express(). The app variable represents our application.

To make the app accessible, we call app.listen() and specify the port number (5000 in this case). This tells the server to listen for incoming requests on that port. Additionally, we provide an optional callback function that logs a message to the console when the server starts running.

By executing this code, our server will start listening on the port5000, and we'll see the message Server is running on port 5000 in the console, confirming that our server is active.

Here are the steps to run the server using either node or nodemon

To run the server usingnode, we would use the command node index.js.

However, with node, we need to manually restart the server whenever we make changes to our code.

To automate this process and enable automatic server updates, we can use nodemon. To installnodemon, run the command

npm install nodemon

Once installed, you can start the server with automatic updates by running nodemon index.js.

With nodemon, we don't have to manually restart the server each time we make changes. It will monitor our files, and when any changes are detected, it will automatically restart the server to reflect those changes.


Now it's time to open your web browser and type localhost:5000. If you see the message Cannot Get/,

don't worry, you're on the right track!

This error occurs because we haven't defined any endpoints yet.

To create endpoints, we have four main HTTP methods:

  1. GET: Used to retrieve data from the server. It's like asking for information. For example, fetching a user's Twitter profile details.
  2. POST: Used to send data to the server. It's like submitting a form for a survey. For example, creating a new user account.
  3. PUT: Used to update existing data on the server. It's like editing information. For example, updating a user's profile.
  4. DELETE: Used to remove data from the server. It's like deleting something. For example, deleting a user's account.

These endpoints represent different actions we can perform on the server. By defining appropriate routes and handling the requests associated with these methods, we can create a fully functional REST API.

So, in order to resolve the Cannot Get/ error, let's define the desired endpoints using these HTTP methods.

Here, I utilized ThunderClient to test and validate these endpoints.

  1. Creating Endpoints:-

so Let's first understand the GET Method

To receive data to the endpoint, we utilize the GET method as follows

app.get("/users", (req, res) => {
  res.json([
    {
      id: 1,
      name: "Saurav",
    },
    {
      id: 2,
      name: "Sonakshi",
    },
    {
      id: 3,
      name: "Deepak",
    },
  ]);
});

Here, when in ThunderClient if we go to localhost:5000/users we see this JSON object

To send data to the endpoint, we utilize the POST method as follows

app.post("/users/4", (req, res) => {
  const name = req.body.name;
  res.send({
    id: 4,
    name: name,
  });
});

To update the existing data, we make use of the PUT request method

app.put("/users/4", (req, res) => {
  const name = req.body.name;
  res.send({
    id: 4,
    name: name,
    message: "Updated Successfully",
  });
});

To remove data from the server, we utilize the DELETE request method

app.delete("/users/4", (req, res) => {
  res.send("Deleted");
});

That's it!

Congratulations 🎉

You've successfully learned how to create your own REST API using the four main HTTP methods: GET, POST, PUT, and DELETE.

Now, it's time to connect your API to a front-end client to enhance the user experience.

Happy Coding 🚀

#blogathon , #showwcase, #growincommunity

You can find me on Twitter

Mail Id: pantsaurav005@gmail.com


4

4

2

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.