I'm working on Express with NodeJS to build some custom APIs. I've successfully build some APIs. Using GET, i'm able to retrieve the data.
Here's my index.js file with all the code.
const express = require('express');
const app = express();
//Create user data.
const userData = [
{
id : 673630,
firstName : 'Prasanta',
lastName : 'Banerjee',
age : 24,
hobby : [
{
coding : ['java', 'python', 'javascript'],
movies : ['action', 'comedy' , 'suspense'],
sports : "basketball"
}
],
oper_sys : ['Mac', 'Windows']
},
{
id : 673631,
firstName : 'Neha',
lastName : 'Bharti',
age : 23
},
{
id : 673651,
firstName : 'Priyanka',
lastName : 'Moharana',
age : 24
},
{
id : 673649,
firstName : 'Shreyanshu',
lastName : 'Jena',
age : 25
},
{
id : 673632,
firstName : 'Priyanka',
lastName : 'Sonalia',
age : 23
},
{
id : 673653,
firstName : 'Bhupinder',
lastName : 'Singh',
age : 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if(user){
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({Error: ['ID Not Found']});
}
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});
Let's say i want to add id:12345 firstName:Michael lastName:Andrews to my userData. How am i supposed to it using POST calls?
I'm looking for code using which i can add new data to my userData, so that every time i do GET on it, i get the updated dataset.