Introduction: Why REST API in JavaScript is Fast and Simple
Creating your own REST API is one of the first steps toward understanding backend development. If you're already familiar with JavaScript, you can write the server-side part of an application in literally half an hour. In this article, we'll break down how to write a REST API in JavaScript using Node.js and the Express framework. We'll create a simple API for managing a To-Do List with support for standard CRUD operations: creating, reading, updating, and deleting data.
This guide is perfect for beginners who want to quickly launch their first server and understand how requests, routes, and middleware work. By the end of the article, you'll have a working API that can be tested in Postman or a browser.
Step 1: Setting Up the Environment and Installing Dependencies
Before writing code, make sure you have Node.js installed (version 16 or higher). If not, download it from the official website. To check, run in the terminal:
node -vnpm -vNow create a folder for the project and initialize it:
mkdir my-apicd my-apinpm init -yInstall the main dependency — the Express framework, which significantly simplifies working with HTTP:
npm install expressAlso install nodemon (optional) for automatic server restart when code changes:
npm install --save-dev nodemonAdd a start script to the package.json file:
"scripts": { "start": "node index.js", "dev": "nodemon index.js"}Step 2: Creating a Basic Server and First Route
Create a file index.js in the project root. Let's start by connecting Express and launching the server on port 3000:
const express = require('express');const app = express();const PORT = 3000;
// Middleware for parsing JSONapp.use(express.json());
// Test routeapp.get('/', (req, res) => { res.send('Hello, world! API is working.');});
app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`);});Start the server with the command npm run dev (if using nodemon) or node index.js. Open your browser and go to http://localhost:3000 — you should see the message "Hello, world! API is working."
Congratulations! You've just written a REST API in JavaScript. Now let's add some real logic.
Step 3: Implementing CRUD Operations for a Task List
Let's create a temporary in-memory data store (an array of objects). In a real project, you would connect a database, but for a 30-minute lesson, this is sufficient.
let tasks = [ { id: 1, title: 'Learn Express', completed: false }, { id: 2, title: 'Write API', completed: true }];
let nextId = 3;Now let's implement four main routes:
GET /tasks — Get all tasks
app.get('/tasks', (req, res) => { res.json(tasks);});POST /tasks — Create a new task
app.post('/tasks', (req, res) => { const { title } = req.body; if (!title) { return res.status(400).json({ error: 'Task title is required' }); } const newTask = { id: nextId++, title, completed: false }; tasks.push(newTask); res.status(201).json(newTask);});PUT /tasks/:id — Update a task
app.put('/tasks/:id', (req, res) => { const id = parseInt(req.params.id); const { title, completed } = req.body; const task = tasks.find(t => t.id === id); if (!task) { return res.status(404).json({ error: 'Task not found' }); } if (title !== undefined) task.title = title; if (completed !== undefined) task.completed = completed; res.json(task);});DELETE /tasks/:id — Delete a task
app.delete('/tasks/:id', (req, res) => { const id = parseInt(req.params.id); const index = tasks.findIndex(t => t.id === id); if (index === -1) { return res.status(404).json({ error: 'Task not found' }); } tasks.splice(index, 1); res.status(204).send();});Step 4: Testing the API
Now your API is ready for testing. You can use Postman, curl, or any other tool for sending HTTP requests. Here are some examples:
// Get all tasksGET http://localhost:3000/tasks
// Create a new taskPOST http://localhost:3000/tasksContent-Type: application/json
{ "title": "Test the API"}
// Update a taskPUT http://localhost:3000/tasks/1Content-Type: application/json
{ "completed": true}
// Delete a taskDELETE http://localhost:3000/tasks/2Try sending different requests and observe how the server responds. This is a great way to understand how REST API works in practice.
Conclusion: What's Next?
You've just created a fully functional REST API in JavaScript in just a few minutes! This is a solid foundation for further learning. Here are a few ideas for what you can add next:
- Connect a real database (for example, MongoDB with Mongoose or PostgreSQL with Prisma)
- Add data validation using libraries like Joi or express-validator
- Implement user authentication (JWT tokens)
- Add pagination and sorting for the task list
- Write automated tests using Jest or Mocha
Now you know how to write a REST API on JavaScript. This skill will be useful for creating full-stack applications, microservices, and even for automating routine tasks. Good luck with your development!