Building a Basic REST API (GET, POST Routes) in Express.
js
Today we discuss how to create a REST API using Express.js, handle GET and POST requests,
and implement a simple live project for managing data.
REST API Basics, Setting Up Express.js, Creating GET & POST Routes
Connecting API with a Database (MongoDB), Testing with Postman, and Mini Project
API Basics & Creating Routes
1️.What is a REST API?
Understanding REST APIs
• REST (Representational State Transfer) is a set of rules for designing web services.
• Uses HTTP methods:
o GET → Retrieve data
o POST → Send data
o PUT → Update data
o DELETE → Remove data
Real-World Examples of REST APIs:
• Weather API → Fetch weather data (GET)
• E-commerce API → Add items to cart (POST), get products (GET)
Hands-on Task:
1. List 3 APIs students use daily (e.g., Google Maps API, YouTube API).
2️.Setting Up Express.js
Install Required Packages
1. Initialize a Node.js Project:
bash
mkdir rest-api && cd rest-api
npm init -y
2. Install Express.js:
npm install express
3. Create server.js and Write Basic Express Server:
const express = require("express");
const app = express();
const PORT = 3000;
// Middleware to parse JSON requests
app.use(express.json());
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Hands-on Task:
1. Run the server:
node server.js
2. Open Postman or browser and check http://localhost:3000/
3.Creating GET & POST Routes
1️. Create a Simple GET Route
app.get("/", (req, res) => {
res.send("Welcome to the REST API!");
});
2️. Create a GET Route to Return Sample Data
const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
app.get("/users", (req, res) => {
res.json(users);
});
3. Create a POST Route to Add Data
app.post("/users", (req, res) => {
const newUser = { id: users.length + 1, name: req.body.name };
users.push(newUser);
res.json(newUser);
});
4. Test Using Postman
• GET http://localhost:3000/users
• POST http://localhost:3000/users (Send { "name": "Charlie" } in JSON body)