Node.js rest API using express
Create a rest API using node.js and express.
Init the project inside your project folder
npm init
Install express
package from npm
.
npm i express
Minimal code to serve 'hello world'
//server.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
})
app.listen(port, () => {
console.log(`App listening on port ${port}`);
})
now run the server using node
node server.js
let test it using curl command or a browser.
curl http://localhost:3000/
the result should be 'Hello World'.
We have seen how to create our first server using express, now we will add some route to: get, post, update and delete data.
//server.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
})
let users = [{
id: 0,
name: 'user1',
age: 28
}, {
id: 1,
name: 'user2',
age: 29
}, {
id: 2,
name: 'user3',
age: 30
}
]
app.get('/users', (req, res) => {
res.status(200).json({
status: 'success',
data: users
});
})
app.post('/users', (req, res) => {
const user = req.body;
users.push(user);
res.status(201).json({
status: 'success',
data: users,
});
})
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
const newUser = req.params.body;
users = users.map((user) => {
if (user.id == userId) {
user.name = newUser.name;
user.age = newUser.age;
}
return user;
});
res.status(201).json({
status: 'success',
data: users,
});
});
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
users = users.map((user) => {
if (user.id != userId) {
return user;
}
});
res.status(204).json({
status: 'success',
data: null,
});
});
app.listen(port, () => {
console.log(`App listening on port ${port}`);
})
Next steps:
- Use Middlewares;
- Structure the project code;
- Use Mongodb as a database;
- Secure the api;
- Write tests;
- Migrate to micro-service architechture;