If you're new to backend development, building an API can feel intimidating.
But good news — with Node.js and Express, you can create a functional API in just a few minutes!
In this guide, you'll learn:
- What an API is
- How to set up a Node.js project
- How to build a simple REST API
- How to test it
- What to learn next
Let’s get started!
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!”
Node.js + Express is one of the easiest ways to build APIs.
Step 1: Initialize Your Project
mkdir my-first-api
cd my-first-api
npm init -y
Step 2: Install Express
npm install express
Step 3: Create Your First Server
Create server.js and add:
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 route
app.get('/api/users', (req, res) => {
res.send([
{ id: 1, name: 'John' },
{ id: 2, name: 'Sarah' }
]);
});
// POST route
let users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Sarah' }
];
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}`);
});
Step 4: Run Your API
node server.js
You should see:
Server running on http://localhost:3000
Try opening:
Congrats — your first API is live!
Step 5: Test the API
Using curl:
curl http://localhost:3000/api/users
Bonus: Add a User With POST
Test with Postman:
{
"name": "Emily"
}
What to Learn Next
- Routing best practices
- Environment variables
- Connecting to MongoDB/PostgreSQL
- Authentication
- Deployment
You’re off to a great start — keep going! 🚀
Top comments (0)