What is REST API and how do you build one with Node.js?
Answer
REST (Representational State Transfer) is an architectural style for designing networked APIs based on HTTP. REST APIs use HTTP methods (GET, POST, PUT, PATCH, DELETE) on resource-based URLs, stateless communication, and typically JSON for data exchange. Building a REST API with Node.js and Express: (1) Setup: const express = require("express"); const app = express(); app.use(express.json());; (2) Define routes matching resources and HTTP methods: app.get("/users", getAll), app.get("/users/:id", getOne), app.post("/users", create), app.put("/users/:id", update), app.delete("/users/:id", remove); (3) Send JSON responses: res.json({ data: users }); (4) Handle errors: res.status(404).json({ error: "Not found" }). REST conventions: use nouns for resource names (not verbs), use status codes correctly (200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error).
Previous
What is the dotenv package and how is it used?
Next
What is JSON.parse() and JSON.stringify() in Node.js?