Introduction to REST_API
Tags: webdev, javascript, beginners, programming
Published: 2024-04-04 09:20:30


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
```
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();

```
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
```
The Output Will Be Look Like:

```
5001 Yes I am Connected
```
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"
    },
```
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;

```
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 = {};
```

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;
  }
```
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;
  }

```
`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);
  }
```

```
http://localhost:5001/api/products?sort=-price
```
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;
```
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**