DEV Community

Cover image for How to Make Your First REST API in Node.js
Leon Martin
Leon Martin

Posted on

How to Make Your First REST API in Node.js

Let’s cut to the chase. In today's tech landscape, with all the changes and layoffs shaking up the industry, having a solid grasp on building REST APIs is more important than ever. Whether you’re trying to boost your portfolio or just automate some tasks, a REST API is a great tool to have in your belt.

In this guide, I’m going to walk you through building a simple REST API using Node.js and Express. No fluff, just practical steps and code you can run on your machine. So, grab your terminal and let’s get started.

Getting Started

First things first: make sure you have Node.js installed. If you haven’t yet, download and install the latest LTS version.

Next, create a new project directory and initialize a new Node.js project:

mkdir my-rest-api
cd my-rest-api
npm init -y
Enter fullscreen mode Exit fullscreen mode

Now, install Express:

npm install express
Enter fullscreen mode Exit fullscreen mode

Building the API

We’re going to create a basic API to manage a list of items. Think of it like a simple to-do app backend. Create a file named index.js in your project directory and open it in your favorite text editor.

Here’s the code:

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

// Middleware to parse JSON bodies
app.use(express.json());

// In-memory storage for our items (acting as our database)
let items = [];

// Endpoint to get all items
app.get('/items', (req, res) => {
  res.json(items);
});

// Endpoint to create a new item
app.post('/items', (req, res) => {
  const { name } = req.body;
  if (!name) {
    return res.status(400).json({ error: 'Name is required' });
  }
  const newItem = { id: items.length + 1, name };
  items.push(newItem);
  res.status(201).json(newItem);
});

// Endpoint to get a single item by ID
app.get('/items/:id', (req, res) => {
  const item = items.find(i => i.id === parseInt(req.params.id));
  if (!item) {
    return res.status(404).json({ error: 'Item not found' });
  }
  res.json(item);
});

// Endpoint to update an item by ID
app.put('/items/:id', (req, res) => {
  const item = items.find(i => i.id === parseInt(req.params.id));
  if (!item) {
    return res.status(404).json({ error: 'Item not found' });
  }
  const { name } = req.body;
  if (!name) {
    return res.status(400).json({ error: 'Name is required' });
  }
  item.name = name;
  res.json(item);
});

// Endpoint to delete an item by ID
app.delete('/items/:id', (req, res) => {
  const id = parseInt(req.params.id);
  items = items.filter(i => i.id !== id);
  res.status(204).send();
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

What’s Happening Here

  • Express Setup: We start by requiring Express and setting up our app. We also define a port (3000) for our server.
  • Middleware: express.json() is used to parse incoming JSON requests. This is crucial because our API will be dealing with JSON data.
  • In-Memory Data Store: For simplicity, we’re using a simple array to store our items. In a real-world application, you’d connect to a database.
  • CRUD Endpoints: We set up endpoints for the typical CRUD operations:
    • GET /items retrieves all items.
    • POST /items creates a new item.
    • GET /items/:id retrieves a specific item.
    • PUT /items/:id updates an item.
    • DELETE /items/:id deletes an item.
  • Running the Server: Finally, the app listens on the specified port, and you’ll see a message in your terminal when it’s running.

Testing Your API

Once your server is running, you can test the API using tools like Postman or even curl in your terminal.

For example, to add a new item:

curl -X POST http://localhost:3000/items -H "Content-Type: application/json" -d '{"name": "Learn Node.js"}'
Enter fullscreen mode Exit fullscreen mode

To fetch all items:

curl http://localhost:3000/items
Enter fullscreen mode Exit fullscreen mode

These commands should help you see your API in action.

Okay, what's next?

Building your first REST API in Node.js doesn’t have to be daunting. With just a few lines of code, you can create a fully functional API that can serve as a foundation for more complex projects.

Remember, the tech environment is always shifting—layoffs, evolving tools, and new paradigms are the norm these days. Keeping your skills sharp with practical projects like this not only makes you more adaptable but also gives you something tangible to show for your hard work.

So, what’s next? Play around with the API, add new endpoints, connect it to a real database, or integrate it with a frontend framework. The possibilities are endless.

Have questions or ideas? Drop a comment below—I’d love to hear your thoughts and experiences!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.