REST API Introduction in Node.js
REST API is a common way for applications to communicate with each other using HTTP requests and responses.
For example, a website may need to display products stored on a server. Instead of storing all product information in the browser, the website can send an HTTP request to a REST API. The server processes the request and returns the product information, commonly in JSON format.
Node.js and Express.js allow us to build REST APIs that receive requests, process data, interact with databases, and return appropriate responses to clients.
1. What Is an API?
API stands for Application Programming Interface. It defines how one software application can communicate with another application or service.
Imagine that you are using an institute website to view available courses. The website requests course information from the server. The server returns the data, and the website displays it. The API provides the communication interface between them.
Client Application
Requests course information
API
Defines how the request and response are exchanged
Server
Processes the request and returns course data
The client does not need to know every internal detail of the server. It only needs to send a request in the format supported by the API and process the response.
2. What Is a REST API?
REST stands for Representational State Transfer. It is an architectural style used to design networked applications. A REST API commonly exposes resources through URLs and uses standard HTTP methods to perform operations on those resources.
For example, an API for managing products might provide endpoints to retrieve products, create a product, update product information, and delete a product.
| HTTP Method | Purpose | Example Endpoint |
|---|---|---|
| GET | Retrieve resource information. | /api/products |
| POST | Create a new resource. | /api/products |
| PUT | Replace a resource representation. | /api/products/101 |
| PATCH | Partially update a resource. | /api/products/101 |
| DELETE | Delete a resource. | /api/products/101 |
3. Why Do We Need REST APIs?
REST APIs allow different applications to exchange data without requiring them to use the same programming language or user interface.
- A website can retrieve information from a server.
- A mobile application can use the same backend API.
- A frontend application can communicate with a database-backed server.
- Applications can expose reusable services to other authorized clients.
- Frontend and backend development can be organized separately.
For example, a Node.js backend may return JSON data while the frontend is developed using React, Angular, or plain JavaScript. The frontend can display the returned data without needing to know how the backend stores it.
4. How a REST API Works
A REST API follows a request-response communication pattern. The client sends an HTTP request to an endpoint, and the server returns a response containing a status code and, when appropriate, response data.
Step 1: Client
Sends an HTTP request
Step 2: Express.js Server
Receives the request and matches the endpoint
Step 3: Application Logic
Processes data or interacts with a database
Step 4: API Response
Returns a status code and response data
Step 5: Client
Reads and displays the response
For example, when a client requests
GET /api/products, the server can retrieve product
records and return them as a JSON array.
5. What Is an Endpoint?
An endpoint is a URL path through which a client accesses a particular API operation or resource.
Consider the following product API endpoints:
| Endpoint | Method | Operation |
|---|---|---|
/api/products |
GET | Retrieve all products |
/api/products/101 |
GET | Retrieve product with ID 101 |
/api/products |
POST | Create a product |
/api/products/101 |
DELETE | Delete product with ID 101 |
Notice that the same path can support different operations
depending on the HTTP method. For example,
GET /api/products retrieves products, while
POST /api/products can create a new product.
6. What Is JSON in a REST API?
JSON stands for JavaScript Object Notation. It is a text-based data format commonly used to exchange structured information between a client and a server.
Example product data returned by an API:
{
"id": 101,
"name": "Laptop",
"price": 55000,
"inStock": true
}
In this example, the product has an ID, a name, a price, and an availability value. The client can read these properties and display them in a user interface.
7. Creating Your First REST API in Express.js
Let us create a simple REST API that returns a list of products. This example uses in-memory data, so the products are not saved permanently in a database.
Step 1: Create a project folder
mkdir rest-api-demo
cd rest-api-demo
npm init -y
npm install express
Step 2: Create app.js
const express = require('express');
const app = express();
const products = [
{
id: 1,
name: 'Laptop',
price: 55000
},
{
id: 2,
name: 'Keyboard',
price: 1500
},
{
id: 3,
name: 'Mouse',
price: 700
}
];
// GET endpoint
app.get('/api/products', (req, res) => {
res.status(200).json(products);
});
app.listen(3000, () => {
console.log('REST API running at http://localhost:3000');
});
Step 3: Start the server
node app.js
Expected terminal output:
REST API running at http://localhost:3000
Step 4: Test the endpoint
Open this URL in your browser:
http://localhost:3000/api/products
Expected JSON response:
[
{
"id": 1,
"name": "Laptop",
"price": 55000
},
{
"id": 2,
"name": "Keyboard",
"price": 1500
},
{
"id": 3,
"name": "Mouse",
"price": 700
}
]
The browser sends a GET request to the endpoint. Express matches
the route, executes its callback, and returns the products using
res.status(200).json(products).
8. Understanding HTTP Status Codes
An HTTP status code indicates the result of a request. REST APIs should return suitable status codes so clients can understand whether an operation succeeded or failed.
| Status Code | Meaning | Typical Use |
|---|---|---|
| 200 | OK | A request completed successfully. |
| 201 | Created | A new resource was created successfully. |
| 400 | Bad Request | The request contains invalid input. |
| 401 | Unauthorized | Valid authentication credentials are missing or invalid. |
| 404 | Not Found | The requested resource or endpoint was not found. |
| 500 | Internal Server Error | An unexpected server-side error occurred. |
Important Points to Remember
- API stands for Application Programming Interface.
- REST stands for Representational State Transfer.
- REST APIs commonly expose resources through URL endpoints.
- HTTP methods describe the operation requested by the client.
- JSON is a common format for exchanging API data.
- Express.js can create API endpoints using route methods such as
app.get(). - Use suitable HTTP status codes for success and error responses.
- The sample product array is temporary in-memory data, not database storage.
Summary
A REST API allows applications to communicate using HTTP requests and responses. It commonly uses resource-based endpoints, HTTP methods, JSON data, and status codes.
With Node.js and Express.js, we can create API endpoints that retrieve, create, update, and delete resources. Understanding these fundamentals prepares us to build individual GET, POST, PUT, PATCH, and DELETE endpoints.