How to Write a REST API in JavaScript in 30 Minutes: A Practical Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: REST API in Half an Hour — It's Real



REST API is the foundation of modern web interaction. Whether you're a frontend developer wanting to understand the backend, or a beginner who wants to quickly create their first server — this guide is for you. We'll break down how to write a full-fledged REST API in JavaScript (Node.js) literally in 30 minutes.



We use a minimal stack: Node.js and Express.js — the most popular framework for creating APIs. No extra code, only practice. By the end of the article, you will have a working server with CRUD operations (create, read, update, delete).



Step 1: Preparation and installing dependencies



First, make sure you have Node.js installed (version 14 or higher). You can download it from the official website. Check the installation:



node -vnpm -v


Create a project folder and navigate into it:



mkdir my-rest-apicd my-rest-api


Initialize the project and install Express:



npm init -ynpm install express


For convenience, install nodemon — it automatically restarts the server when code changes:



npm install --save-dev nodemon


Now open package.json and replace the "scripts" section with:



"scripts": {  "start": "node index.js",  "dev": "nodemon index.js"}


Great! Everything is ready for writing code.



Step 2: Writing the basic server and first endpoint



Create a file index.js in the project root. Let's start by importing Express and setting up the port:



const express = require('express');const app = express();const PORT = 3000;

// Middleware for parsing JSONapp.use(express.json());

// Simple test endpointapp.get('/', (req, res) => { res.send('My REST API is working!');});

// Start the serverapp.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`);});


Start the server with the command:



npm run dev


Go to http://localhost:3000 in your browser — you should see the message "My REST API is working!".



Adding a database simulation



For simplicity, we will store data in memory (an array). In a real project, you would connect MongoDB or PostgreSQL, but this is sufficient for learning.



// Database simulationlet users = [  { id: 1, name: 'Alexey', email: 'alex@example.com' },  { id: 2, name: 'Maria', email: 'maria@example.com' }];let nextId = 3;


Step 3: Implementing CRUD operations



Now let's create full-fledged endpoints for working with users. We will implement four main HTTP methods: GET, POST, PUT, DELETE.



GET — retrieving all users



// Get all usersapp.get('/api/users', (req, res) => {  res.json(users);});

// Get user by IDapp.get('/api/users/:id', (req, res) => { const id = parseInt(req.params.id); const user = users.find(u => u.id === id); if (!user) { return res.status(404).json({ message: 'User not found' }); } res.json(user);});


POST — creating a new user



// Create userapp.post('/api/users', (req, res) => {  const { name, email } = req.body;    // Simple validation  if (!name || !email) {    return res.status(400).json({ message: 'Name and email are required' });  }    const newUser = {    id: nextId++,    name,    email  };    users.push(newUser);  res.status(201).json(newUser);});


PUT — updating a user



// Update userapp.put('/api/users/:id', (req, res) => {  const id = parseInt(req.params.id);  const { name, email } = req.bod                

Blogs

Book Recommendations