How to Build Your First REST API with Node.js and Express (From Someone Who Was Scared at First)
Arbythecoder

Arbythecoder @arbythecoder

About: Freelance Backend Developer | Python & Node.js | SRE & Cloud Security Engineer | Technical Writer with 24k+ Views on Dev.to |AI\ML Enthusiast

Location:
lagos ,nigeria
Joined:
Jan 5, 2023

How to Build Your First REST API with Node.js and Express (From Someone Who Was Scared at First)

Publish Date: May 1
2 0

I still remember the first time I opened an empty app.js file in VS Code. No idea where to start. REST API? I barely understood what "route" meant.
But I kept going, This is the guide I wish I had when I started my journey into backend development.

1. What is a REST API

Think of a REST API like a restaurant experience. You (the client) sit at a table and look at a menu (the API documentation). When you're ready to order, you call over a waiter (send a request) who takes your order to the kitchen (server). The kitchen prepares your food (processes the request), and the waiter returns it (the response).

In this analogy:

  • GET is like asking, "What's the special today?"
  • POST is like placing a new order
  • PUT is like saying, "Actually, can I change my side dish?"
  • DELETE is like canceling your order

That's REST in a nutshell - a set of conventions for requesting and modifying resources over HTTP.

2. Setting Up Node.js and Express

First, make sure you have Node.js installed (check with node -v in your terminal). Then:

  1. Create a new folder for your project and navigate to it:
mkdir my-first-api
cd my-first-api
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a Node.js project:
npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install Express:
npm install express
Enter fullscreen mode Exit fullscreen mode
  1. Create your main file:
touch app.js
Enter fullscreen mode Exit fullscreen mode
  1. Open app.js and add the following code:
const express = require('express');
const app = express();
const PORT = 3000;

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

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

3. Creating Your First Route

Let's add a simple welcome route to make sure everything's working:

app.get('/api/welcome', (req, res) => {
  res.json({ message: "Hello, world!" });
});
Enter fullscreen mode Exit fullscreen mode

Now run your server:

node app.js
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:3000/api/welcome. You should see: {"message":"Hello, world!"}. Congratulations! You've created your first API endpoint! 🎉

4. Building a Simple CRUD API for "Mocktails"

Let's create a simple in-memory database for mocktails (non-alcoholic cocktails).

First, add this to your app.js file:

// Our "database" (in-memory for now)
let mocktails = [
  { id: 1, name: "Virgin Mojito", ingredients: ["Mint", "Lime", "Sugar", "Soda"] },
  { id: 2, name: "Shirley Temple", ingredients: ["Ginger ale", "Grenadine", "Maraschino cherry"] }
];

// Helper to find mocktail by ID
function findMocktailIndex(id) {
  return mocktails.findIndex(m => m.id === parseInt(id));
}
Enter fullscreen mode Exit fullscreen mode

CREATE - Add a new mocktail

app.post('/api/mocktails', (req, res) => {
  const newMocktail = {
    id: mocktails.length + 1,
    name: req.body.name,
    ingredients: req.body.ingredients
  };

  mocktails.push(newMocktail);
  res.status(201).json(newMocktail);
});
Enter fullscreen mode Exit fullscreen mode

READ - Get all mocktails

app.get('/api/mocktails', (req, res) => {
  res.json(mocktails);
});
Enter fullscreen mode Exit fullscreen mode

READ - Get a single mocktail

app.get('/api/mocktails/:id', (req, res) => {
  const index = findMocktailIndex(req.params.id);

  if (index === -1) {
    return res.status(404).json({ error: "Mocktail not found" });
  }

  res.json(mocktails[index]);
});
Enter fullscreen mode Exit fullscreen mode

UPDATE - Modify a mocktail

app.put('/api/mocktails/:id', (req, res) => {
  const index = findMocktailIndex(req.params.id);

  if (index === -1) {
    return res.status(404).json({ error: "Mocktail not found" });
  }

  const updatedMocktail = {
    id: parseInt(req.params.id),
    name: req.body.name || mocktails[index].name,
    ingredients: req.body.ingredients || mocktails[index].ingredients
  };

  mocktails[index] = updatedMocktail;
  res.json(updatedMocktail);
});
Enter fullscreen mode Exit fullscreen mode

DELETE - Remove a mocktail

app.delete('/api/mocktails/:id', (req, res) => {
  const index = findMocktailIndex(req.params.id);

  if (index === -1) {
    return res.status(404).json({ error: "Mocktail not found" });
  }

  const deletedMocktail = mocktails[index];
  mocktails = mocktails.filter(m => m.id !== parseInt(req.params.id));

  res.json(deletedMocktail);
});
Enter fullscreen mode Exit fullscreen mode

5. Testing with Postman

Postman is like your API's best friend. It lets you test endpoints without writing any frontend code.

  1. Download Postman from postman.com
  2. Create a new collection called "Mocktail API"
  3. Add requests for each endpoint:

GET all mocktails:

GET a single mocktail:

CREATE a new mocktail:

{
  "name": "Pineapple Sunrise",
  "ingredients": ["Pineapple juice", "Orange juice", "Grenadine"]
}
Enter fullscreen mode Exit fullscreen mode

UPDATE a mocktail:

{
  "name": "Tropical Sunrise",
  "ingredients": ["Pineapple juice", "Orange juice", "Grenadine", "Lime"]
}
Enter fullscreen mode Exit fullscreen mode

DELETE a mocktail:

Pro tip: When you see that "200 OK" or "201 Created" status, it's like getting a gold star! ⭐

6. What I Learned the Hard Way

Mistakes I Made:

  • Forgetting express.json(): I spent hours wondering why my POST requests weren't working, only to realize I hadn't added this middleware. Without it, Express can't read JSON from request bodies!
  • Not checking route parameters: I would get confused when my routes weren't matching, not realizing :id in /api/mocktails/:id needed to be accessed with req.params.id.
  • Missing status codes: I used to just send responses without proper status codes. Now I know 201 for creation, 404 for not found, etc.

Things That Finally "Clicked":

  • Middleware flow: Understanding that requests flow through middleware in order was a game-changer.
  • The request/response cycle: Each request gets exactly one response (even if it's an error).
  • RESTful patterns: Using the right HTTP methods for the right operations makes your API intuitive.

What I'd Do Differently:

  • Start with a simple project structure from the beginning
  • Learn about error handling earlier
  • Use environment variables for configuration
  • Write tests from the start

7. A Word to Beginners

If you feel confused, you're not dumb — you're just early in the process. Every developer goes through this. Your first API doesn't need to be perfect. It just needs to exist.

When I made my first successful request and saw data coming back, I felt like I had unlocked a superpower. You will too!

Start small. Build consistently. Google everything. And remember: even experienced developers are constantly learning.

Next Steps

Once you're comfortable with the basics:

  • Connect to a real database (MongoDB or PostgreSQL)
  • Add input validation with Joi or express-validator
  • Implement authentication with JWT
  • Deploy your API to Heroku or Render

The code for this tutorial is available on my GitHub repository.

Happy coding! 🚀

Comments 0 total

    Add comment