JavaScript technologies

REST API

Horváth, Győző
senior lecturer
horvath.gyozo@inf.elte.hu

Financed from the financial support ELTE won from the Higher Education Restructuring Fund of the Hungarian Government

REST API

REST API

Representational State Transfer (REST) Application Programming Interface (API)

  • Data access through HTTP protocol
  • CRUD operations on data source
  • with HTTP methods (GET, POST, DELETE, PUT/PATCH)
  • request/response (generally) in JSON format

REST API example

  • GET /people: querying all people
  • GET /people/john: querying an element with john identifier from model people
  • POST /people: Inserting new element into people model
  • DELETE /people/john: Deleting element with john identifier from model people
  • PUT /people/john: Updating element with john identifier in model people

REST

Representational State Transfer

create  → POST   /collection
read    → GET    /collection[/id]
update  → PUT    /collection/id
patch   → PATCH  /collection/id
delete  → DELETE /collection[/id]

Task

Make a REST API endpoint for storing code snippets!

Use NeDB for storing the data!

REST endpoints

Router

var express = require('express');
var router = express.Router();

var Datastore = require('nedb'),
    db = new Datastore({ filename: 'snippets.nedb', autoload: true });

router
    .get('/', function(req, res, next) {
        
    })
    .post('/', function(req, res) {
        
    })
    .put('/:id', function (req, res) {
        
    })
    .delete('/:id', function (req, res) {
        
    });

module.exports = router;

Solution

var express = require('express');
var router = express.Router();

var Datastore = require('nedb'),
    db = new Datastore({ filename: 'snippets.nedb', autoload: true });

router
    .get('/', function(req, res, next) {
        db.find({}, function (err, docs) {
            res.json(docs);
        });
    })
    .post('/', function(req, res) {
        var doc = req.body;
        db.insert(doc, function (err, newDoc) {
            res.json(newDoc);
        });
    })
    .put('/:id', function (req, res) {
        var id = req.params.id;
        var sn = req.body;
        db.update({_id: id}, sn, {}, function (err, num, newDoc) {
            res.json(newDoc);
        });
    })
    .patch('/:id', function (req, res) {
        var id = req.params.id;
        var sn = req.body;
        db.update({_id: id}, {$set: sn}, {}, function (err, num, newDoc) {
            res.json(newDoc);
        });
    })
    .delete('/:id', function (req, res) {
        var id = req.params.id;
        db.remove({_id: id}, {}, function (err, num) {
            res.status(204).send('');
        });
    });

module.exports = router;

Testing

Tests

  • create a new element in the database with a POST method
  • query all elements with a GET method
  • select one element with a GET method
  • update/delete an element with PUT and DELETE methods