đī¸ Building a Simple In-Memory JSON API Server Using Node.js http Module
Introduction
An API (Application Programming Interface) allows applications to communicate by exchanging data over HTTP. Using Node.js's built-in http module, you can create a simple REST-style API without installing external libraries. In this tutorial, you'll build an API that stores data in memory using a JavaScript array and responds with JSON.
Information
Since the data is stored in memory, it exists only while the server is running. Restarting the server clears all stored data.
Learning Objectives
- Create an HTTP server using the http module.
- Store data in an in-memory JavaScript array.
- Handle GET and POST requests.
- Parse JSON request bodies.
- Return JSON responses with proper HTTP status codes.
How the API Works
đ Client Sends Request
đ Server Checks URL and HTTP Method
đĻ Read or Update In-Memory Data
đ Convert Data to JSON
đ¨ Send JSON Response
Project Structure
đ json-api
đ server.js
đ package.json (optional)
Creating the API Server
Begin by importing the http module and creating an array that will temporarily store user records.
server.js
const http = require("http");
const users = [];
const server = http.createServer((req, res) => {
// GET /users
if (req.url === "/users" && req.method === "GET") {
res.writeHead(200, {
"Content-Type": "application/json"
});
return res.end(JSON.stringify(users));
}
// POST /users
if (req.url === "/users" && req.method === "POST") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
try {
const user = JSON.parse(body);
users.push(user);
res.writeHead(201, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
message: "User added successfully",
data: user
}));
} catch (error) {
res.writeHead(400, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
error: "Invalid JSON"
}));
}
});
return;
}
// 404 Route
res.writeHead(404, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
error: "Route not found"
}));
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});Understanding the Code
| Section | Purpose |
|---|---|
| users | Stores data temporarily in memory. |
| GET /users | Returns all stored users. |
| POST /users | Receives and stores a new user. |
| req.on("data") | Reads incoming request data in chunks. |
| req.on("end") | Processes the complete request body. |
| JSON.parse() | Converts JSON text into a JavaScript object. |
| JSON.stringify() | Converts JavaScript objects into JSON strings. |
Request Processing Flow
HTTP Request
GET /users
POST /users
Unknown Route
Return Users Array
Read Request Body
Parse JSON
Store User in Array
Return Success Response
Return 404 Response
Reading the Request Body
Incoming request data is received as a stream. You must collect all chunks before converting the data into a JavaScript object.
Reading JSON request data
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
const data = JSON.parse(body);
console.log(data);
});Important
Always wrap JSON.parse() inside a try...catch block to prevent invalid JSON from crashing the server.
Testing the API
Retrieve All Users
GET request
GET /users HTTP/1.1
Host: localhost:3000Add a New User
POST request
POST /users HTTP/1.1
Host: localhost:3000
Content-Type: application/json
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}Expected JSON Response
Success response
{
"message": "User added successfully",
"data": {
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
}Sample Workflow
đ Start Server
đ¨ Send POST Request
đ¤ User Stored in Memory
đĨ Send GET Request
đ Receive Updated User List
HTTP Status Codes Used
| Status Code | Meaning | When Used |
|---|---|---|
| 200 | OK | Successful GET request |
| 201 | Created | New user successfully added |
| 400 | Bad Request | Invalid JSON received |
| 404 | Not Found | Unknown route requested |
Advantages of In-Memory Storage
- Very simple to implement.
- No database setup required.
- Ideal for learning REST APIs.
- Fast access because data resides in memory.
Limitations
- All data is lost when the server restarts.
- Not suitable for production applications.
- Cannot share data across multiple server instances.
- Memory usage increases as more data is stored.
Warning
In production environments, replace the in-memory array with a persistent database such as MongoDB, PostgreSQL, MySQL, or SQLite.
Possible Improvements
- Add support for PUT requests to update existing users.
- Add support for DELETE requests to remove users.
- Generate unique IDs automatically.
- Validate incoming request data.
- Separate routing and request handlers into different modules.
Basic API
GET
POST
Future Enhancements
PUT
DELETE
Validation
Database Integration
Best Practice
Always set the correct Content-Type, return appropriate HTTP status codes, validate client input, and handle malformed JSON gracefully to build reliable APIs.
Official Documentation
Node.js HTTP Module Documentation
Summary
Summary
You built a simple in-memory JSON API server using Node.js's built-in http module. The server handles GET and POST requests, stores data in a JavaScript array, parses JSON request bodies, returns JSON responses with appropriate HTTP status codes, and demonstrates the core concepts behind RESTful API development without external frameworks.