Node.js RESTful API

๐Ÿš€ Node.js RESTful API (Complete Guide)

A RESTful API is an API that follows REST principles and allows clients to interact with a server using HTTP methods:

Method Purpose
GET Read data
POST Create data
PUT Update data
DELETE Remove data

We will build a simple REST API using Node.js + Express.js.


๐Ÿ“ฆ 1. Project Setup

mkdir node-rest-api
cd node-rest-api
npm init -y

Install Express:

npm install express

๐Ÿ—๏ธ 2. Create Basic Server

Create server.js:


 

Run the server:

node server.js

๐Ÿ—‚๏ธ 3. Sample Data (Fake Database)

We’ll store data temporarily in an array.


๐Ÿงฉ 4. REST API Endpoints

โœ… GET All Users


โœ… GET Single User by ID


 


โœ… POST Create New User


 


โœ… PUT Update User


 


โœ… DELETE Remove User


๐Ÿ“˜ Full Express REST API Example

Here is the full server.js:


 


๐Ÿงช Testing the API

You can test it using:

โœ” Postman
โœ” Thunder Client (VS Code)
โœ” curl

Example curl test:

curl http://localhost:3000/api/users

๐Ÿ” Bonus: Add CORS Support

npm install cors


โš™๏ธ Bonus: Use Nodemon (Auto Restart)

npm install --save-dev nodemon

Add to package.json:

Run:

npm start

You may also like...