A Beginner-Friendly Guide to Building Your First API Using Node.js
Source: Dev.to
Introduction
If you’re new to backend development, building an API can feel intimidating.
Good news — with Node.js and Express you can create a functional API in just a few minutes.
What Is an API?
An API (Application Programming Interface) allows different applications to communicate with each other.
Example
- Frontend: “Give me all users.”
- Backend API: “Here you go!”
Setting Up the Project
mkdir my-first-api
cd my-first-api
npm init -y
npm install express
Creating the Server
Create a file named server.js and add the following code:
const express = require('express');
const app = express();
app.use(express.json());
// Home route
app.get('/', (req, res) => {
res.send({ message: 'Welcome to your first Node.js API!' });
});
// Sample GET route
app.get('/api/users', (req, res) => {
res.send([
{ id: 1, name: 'John' },
{ id: 2, name: 'Sarah' }
]);
});
// In‑memory users array
let users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Sarah' }
];
// POST route to add a user
app.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).send(newUser);
});
// Start server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Run the server:
node server.js
You should see:
Server running on http://localhost:3000
Running the API
Open your browser or use a tool like curl or Postman to interact with the endpoints.
- Home:
http://localhost:3000 - Get users:
http://localhost:3000/api/users
Using curl
curl http://localhost:3000/api/users
Using Postman (POST)
{
"name": "Emily"
}
Send the request to http://localhost:3000/api/users to add a new user.
Next Steps
- Routing best practices – organize routes in separate modules.
- Environment variables – store configuration (e.g., port, DB credentials) with
dotenv. - Database integration – connect to MongoDB, PostgreSQL, etc., instead of using an in‑memory array.
- Authentication – implement JWT or session‑based auth for protected routes.
- Deployment – deploy to platforms like Heroku, Vercel, or Render.
You’re off to a great start — keep going! 🚀