DEV Community

Cover image for Introduction to REST_API
Gyanshu Kumar
Gyanshu Kumar

Posted on

Introduction to REST_API

RESTful APIs are a crucial component of modern software development. By adhering to the principles of REST, they provide a standardized way for systems to communicate over HTTP. RESTful APIs allow developers to create more flexible and scalable applications that can be easily integrated with other systems. These APIs make it possible to manipulate resources using HTTP methods like GET, POST, PUT, and DELETE, and identify resources using URIs. By keeping the state of the system on the client side, RESTful APIs make it easier to build applications that are more resilient and adaptable to change. If you're looking to build modern, flexible applications, RESTful APIs are an essential tool in your toolkit.

Before creating a REST API, you typically need to set up a server to handle incoming HTTP requests. Express.js is a popular choice for creating servers in Node.js due to its simplicity and flexibility. Here's a basic overview of how you can create a server using Express:

To install Express:
Open Vs Code Inside Terminal write

npm install Express
Enter fullscreen mode Exit fullscreen mode

Create a file eg. app.js
Code For Creating Server Using Express:

require("dotenv").config();
const express = require('express');
const app = express();
const connectDB = require("./db/connect");

const PORT = process.env.PORT || 5001;

const products_routes = require("./routes/products");

app.get("/", (req, res) => {
    res.send("Hi I am Live ");
});

// middleware or to set router
app.use("/api/products", products_routes);

const start = async () => {
    try {
        await connectDB(process.env.MONGODB_URL);
        app.listen(PORT, () => {
            console.log(`${PORT} Yes I am Connected`);
        });
    } catch (error) {
        console.log(error);
    }
}

start();

Enter fullscreen mode Exit fullscreen mode

This code sets up an Express server with routes for handling product-related requests. It connects to a MongoDB database and starts the server on a specified port.

First, the code imports necessary dependencies like Express and MongoDB connection function. Then, it defines a route for the root URL ("/") to respond with "Hi I am Live".

Next, it mounts the product routes at "/api/products". This means that any requests to URLs beginning with "/api/products" will be handled by the product routes defined in the code.

After that, the code establishes a connection to MongoDB using the provided URL. This is necessary in order to interact with the database and perform CRUD (create, read, update, delete) operations on the product data.

Finally, the code starts the server on a specified port and logs a confirmation message. This means that the server is now running and ready to handle incoming requests.

To Run This code Simply Write in your Terminal:

node app.js
Enter fullscreen mode Exit fullscreen mode

The Output Will Be Look Like:

5001 Yes I am Connected
Enter fullscreen mode Exit fullscreen mode

Open Your Chrome Browser Then Search:
https://localhost:5001

result: Hi I am Live

I have created a REST API with pagination, searching, sorting, and filtering functionalities.
Suppose Our Product Data Look Like:

{
      "name": "iPhone 13",
      "price": 999,
      "featured": true,
      "rating": 4.9,
      "createdAt": "2024-03-05T00:00:00.000Z",
      "company": "apple"
    },
    {
      "name": "iPhone 11",
      "price": 999,
      "featured": true,
      "rating": 4.9,
      "createdAt": "2024-03-05T00:00:00.000Z",
      "company": "apple"
    },
    {
      "name": "Galaxy S22",
      "price": 1099,
      "featured": false,
      "rating": 4.8,
      "createdAt": "2024-03-05T00:00:00.000Z",
      "company": "samsung"
    },
Enter fullscreen mode Exit fullscreen mode

This File is stored in JSON Format.
To access these Files We have to store all these Files on Our Database
To Connect With MongoDB:

const mongoose = require("mongoose");

const connectDB = async (uri) => {
  try {

    await mongoose.connect(uri);
    console.log("MongoDB connected successfully");
  } catch (error) {
    console.error("MongoDB connection error:", error);
    throw error; // Rethrow for external handling
  }
};

module.exports = connectDB;

Enter fullscreen mode Exit fullscreen mode

After Writing this code You have to your MongoDB ID and Password inside your .env folder

const getAllProducts = async (req, res) => {

  const { company, name, featured, sort, select } = req.query;
  const queryObject = {};
Enter fullscreen mode Exit fullscreen mode

Now We can apply All REST API Filteration on our Data
if We Want to See featured Product Only then we apply
suppose We have to see the Product Whose featured is True

if (featured){
    queryObject.featured = featured;
  }
Enter fullscreen mode Exit fullscreen mode

open POSTMAN Create Workspace Select GET option write https://localhost:5001/product/featured:true
The result filters only that Product Whose Featured is True.

For Companywise Product

if (company){
    queryObject.company = company;
  }

Enter fullscreen mode Exit fullscreen mode

https://localhost:5001/company = apple
It Shows Apple Product Only

For Sorting by Price

if (sort){
    let sortFix = sort.split(",").join(" ");
    apiData = apiData.sort(sortFix);
  }
Enter fullscreen mode Exit fullscreen mode
http://localhost:5001/api/products?sort=-price
Enter fullscreen mode Exit fullscreen mode

Now We want to see only 10 Product per Page the we apply pagination Formula

let page = Number(req.query.page) || 1;
  let limit = Number(req.query.limit) || 10;

  // Formula of Pagination
  let skip = (page - 1) * limit;
Enter fullscreen mode Exit fullscreen mode

inside POSTMAN http://localhost:5001/api/products?page=2
The features mentioned are indeed commonly used in REST APIs. If you would like to learn more about these features or explore additional content, you can visit the official Express.js website at expressjs.com.

                **THANK YOU** 
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
rohiitbagal profile image
Rohit

Are you know something about private route means like auth please tell me something about it ..

Collapse
 
gyanshukumar profile image
Gyanshu Kumar

Yes, Before accessing Private route. First We need to authenticate themselves, usually by providing credentials such as a username and password.
How to create local Authentication using passport.org .
You Can visite my GitHub repository https://github.com/Gyanshu-Kumar/Authentication-in-Express and for detail content you can also visit passport.org