Last active
April 22, 2020 10:14
-
-
Save piyushgarg-dev/96a558d2c9eb6c80125ffc587f73697a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import the Express using require() module | |
const express = require('express'); | |
// Initalize express app | |
const app = express(); | |
// Lets create Fake Data for api | |
const userData = [ | |
{ | |
id: 1, | |
name: 'Jhon', | |
age: 20 | |
}, | |
{ | |
id: 2, | |
name: 'Jane', | |
age: 23 | |
}, | |
{ | |
id: 3, | |
name: 'Tim', | |
age: 34 | |
}, | |
]; | |
// Create Endpoints for API | |
// Endpoint 1 | |
app.get('/api', function(req, res){ | |
res.send('Welcome to our API') | |
}) | |
// Endpoint 2 | |
app.get('/api/users', function(req, res){ | |
res.json(userData); | |
}) | |
// Endpoint 3 | |
app.get('/api/user/:id', function(req, res){ | |
const id = req.params.id; | |
const user = userData.find(user => user.id == id); | |
if (user) { | |
res.json(user) | |
} | |
else { | |
res.send('No User Found') | |
} | |
}) | |
// Start the Server | |
const PORT = 3000; | |
app.listen(PORT, function(){ | |
console.log('Server Started') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment