Express.js Basics: Setting Up Your First API
New to backend development? Let's build a simple REST API with Express.js from scratch.
Why Express?
Express.js has been around forever (in JavaScript years), and there's a reason it's still the go-to for Node.js APIs. It's minimal, flexible, and has a massive ecosystem.
This is Part 1 of a series where we'll build out a complete backend.
Getting Started
mkdir my-api
cd my-api
npm init -y
npm install express
Hello World
Create `index.js`:
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.json({ message: 'Hello World!' });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Run it:
node index.js
That's it. You have an API.
Adding Routes
Let's add a simple resource - users:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET single user
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
});
Handling POST Requests
Need to parse JSON bodies first:
app.use(express.json());
// POST new user
app.post('/api/users', (req, res) => {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: 'Name is required' });
}
const newUser = {
id: users.length + 1,
name
};
users.push(newUser);
res.status(201).json(newUser);
});
Project Structure
As your API grows, organize it:
my-api/
├── index.js
├── routes/
│ └── users.js
├── controllers/
│ └── userController.js
├── middleware/
│ └── errorHandler.js
└── package.json
What's Next
In the next post, we'll cover:
- Middleware and error handling
- Input validation
- Connecting to a database
The concepts here apply whether you're building a side project or a production API. Start simple, add complexity as needed.