step to run 1: npm install 2: npm install https://github.com/mapbox/node-sqlite3/tarball/master 3: node restapi.js
Last active
October 24, 2017 09:56
-
-
Save ovarunendra/24c0b74288700c6b3904 to your computer and use it in GitHub Desktop.
rest-api using node.js and sqlite3
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
{ | |
"name": "restapi", | |
"version": "1.0.0", | |
"description": "", | |
"main": "restapi.js", | |
"dependencies": { | |
"express": "^4.13.1", | |
"sqlite3": "^3.0.9" | |
}, | |
"devDependencies": {}, | |
"scripts": { | |
"start": "node restapi.js" | |
}, | |
"author": "Varunendra Pratap Singh", | |
"license": "ISC" | |
} |
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
var sqlite3 = require('sqlite3').verbose(); | |
var db = new sqlite3.Database('data/demodb02'); | |
db.serialize(function() { | |
db.run("CREATE TABLE IF NOT EXISTS counts (key TEXT, value INTEGER)"); | |
db.run("INSERT INTO counts (key, value) VALUES (?, ?)", "counter", 0); | |
}); | |
var express = require('express'); | |
var restapi = express(); | |
restapi.get('/data', function(req, res){ | |
db.get("SELECT value FROM counts", function(err, row){ | |
res.json({ "count" : row.value }); | |
}); | |
}); | |
restapi.post('/data', function(req, res){ | |
db.run("UPDATE counts SET value = value + 1 WHERE key = ?", "counter", function(err, row){ | |
if (err){ | |
console.err(err); | |
res.status(500); | |
} | |
else { | |
res.status(202); | |
} | |
res.end(); | |
}); | |
}); | |
restapi.listen(3000); | |
console.log("Submit GET or POST to http://localhost:3000/data"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do i insert data into my tables?