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:
- Create a new folder for your project and navigate to it:
mkdir my-first-api
cd my-first-api
- Initialize a Node.js project:
npm init -y
- Install Express:
npm install express
- Create your main file:
touch app.js
- 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}`);
});
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!" });
});
Now run your server:
node app.js
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));
}
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);
});
READ - Get all mocktails
app.get('/api/mocktails', (req, res) => {
res.json(mocktails);
});
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]);
});
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);
});
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);
});
5. Testing with Postman
Postman is like your API's best friend. It lets you test endpoints without writing any frontend code.
- Download Postman from postman.com
- Create a new collection called "Mocktail API"
- Add requests for each endpoint:
GET all mocktails:
- Method: GET
- URL: http://localhost:3000/api/mocktails
GET a single mocktail:
- Method: GET
- URL: http://localhost:3000/api/mocktails/1
CREATE a new mocktail:
- Method: POST
- URL: http://localhost:3000/api/mocktails
- Body (raw JSON):
{
"name": "Pineapple Sunrise",
"ingredients": ["Pineapple juice", "Orange juice", "Grenadine"]
}
UPDATE a mocktail:
- Method: PUT
- URL: http://localhost:3000/api/mocktails/3
- Body (raw JSON):
{
"name": "Tropical Sunrise",
"ingredients": ["Pineapple juice", "Orange juice", "Grenadine", "Lime"]
}
DELETE a mocktail:
- Method: DELETE
- URL: http://localhost:3000/api/mocktails/3
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 withreq.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! 🚀