Skip to content

Instantly share code, notes, and snippets.

@bbachi
Last active February 13, 2019 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbachi/c210d96b2d9fc3fb9c8ae2aa217eae99 to your computer and use it in GitHub Desktop.
Save bbachi/c210d96b2d9fc3fb9c8ae2aa217eae99 to your computer and use it in GitHub Desktop.
How to write production ready Node.js Rest API With javascript
var express = require("express"),
bodyParser = require("body-parser"),
app = express(),
port = 3070;
// array to hold users
const users = [{firstName:"fnam1",lastName:"lnam1",userName:"username1"}];
app.use(bodyParser.json());
// Default user
app.get("/", function(req, res) {
res.send("App works!!");
})
// request to get all the users
app.get("/users", function(req, res) {
res.json(users);
})
// request to get all the users by userName
app.get("/users/:userName", function(req, res) {
let user = users.filter(function(user){
if(req.params.userName === user.userName){
return user;
}
})
res.json(user);
})
// request to post the user
// req.body has object of type {firstName:"fnam1",lastName:"lnam1",userName:"username1"}
app.post("/user", function(req, res) {
users.push(req.body);
res.json(users);
})
app.listen(port, function(err) {
console.log("running server on from port:::::::" + port);
});
{
"name": "user_api",
"version": "1.0.0",
"description": "sample rest api",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Bhargav Bachina",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment