Backend 03 - REST APIs and HTTP Methods

Code SubtleCode Subtle
2 min read

๐Ÿ—“๏ธ Day - 3: REST APIs and HTTP Methods


๐ŸŒ What are REST APIs?

  • REST (Representational State Transfer) is a type of API that follows specific rules and guidelines for communication.

  • It uses HTTP methods like:

    • GET

    • POST

    • PUT

    • DELETE

  • It defines fixed standards for how requests and responses should be structured.


๐Ÿ“จ Ways to Send Data in Requests

1. req.body

  • Hidden in the request payload.

  • Best for larger, sensitive, or complex data (like passwords).

  • Typically used in POST, PUT, and PATCH requests.

2. req.query

  • Data sent in the URL after ? as key-value pairs.

  • Ideal for small, optional parameters.

  • Avoid using it for sensitive or complex data.

  • Example:

      GET /search?gender=male&age=24
    

3. req.params

  • Data sent as part of the API path.

  • Commonly used for identifying specific resources.

  • Example:

      GET /user/ankur_bit_io
    
  • Accessed in code as:

      req.params.username
    

๐Ÿงพ REST API Methods

MethodPurpose
GETRetrieve data from the server.
POSTSend new data to the server (create).
PATCHUpdate existing data on the server.
DELETERemove/delete data from the server.

๐Ÿ’ก Example Use Case:
A social media app like x.com may use:

  • req.params to fetch user profiles (/user/:username)

  • req.query to filter search results (/search?gender=male)

  • req.body for login forms or post creation

const express = require("express");

const app = express(); //server is created

//this is a middleware
app.use(express.json());

let notes = []

app.post("/notes", (req, res) => {
  console.log(req.body);
  notes.push(req.body)
  res.json({
    message:"notes added successfully",
    notes:notes
  })
});


//starting the server
app.listen(3000, () => {
  console.log("server is running on port 3000");
});
npx nodemon server.js //it checks continues changes on the server
0
Subscribe to my newsletter

Read articles from Code Subtle directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Code Subtle
Code Subtle

At Code Subtle, we empower aspiring web developers through personalized mentorship and engaging learning resources. Our community bridges the gap between theory and practice, guiding students from basics to advanced concepts. We offer expert mentorship and write interactive, user-friendly articles on all aspects of web development. Join us to learn, grow, and build your future in tech!