Introduction to Restify
Restify is a Node.js web service framework optimized for building semantically correct RESTful web services. It is focused on providing robust and reliable services with powerful routing and contextualizable request and response objects.
Setting Up Restify
const restify = require('restify'); const server = restify.createServer(); server.listen(8080, function() { console.log('%s listening at %s', server.name, server.url); });
Core APIs
Create Server
const server = restify.createServer({ name: 'myapp', version: '1.0.0' });
Routing
server.get('/hello/:name', function(req, res, next) { res.send('hello ' + req.params.name); return next(); }); server.post('/hello', function(req, res, next) { res.send(201, 'hello ' + req.body.name); return next(); });
Middleware Integration
server.use(restify.plugins.acceptParser(server.acceptable)); server.use(restify.plugins.queryParser()); server.use(restify.plugins.bodyParser());
Error Handling
server.on('restifyError', function(req, res, err, callback) { console.error(err.stack); res.send(err); callback(); });
Contextualized Request and Response
server.get('/context', function(req, res, next) { const data = { timestamp: new Date(), method: req.method, query: req.query }; res.send(data); return next(); });
Building an Application
Below is an example of a complete Restify application that demonstrates the use of the APIs discussed above.
const restify = require('restify'); const server = restify.createServer({ name: 'myapp', version: '1.0.0' }); server.use(restify.plugins.acceptParser(server.acceptable)); server.use(restify.plugins.queryParser()); server.use(restify.plugins.bodyParser()); server.get('/hello/:name', function(req, res, next) { res.send('hello ' + req.params.name); return next(); }); server.post('/hello', function(req, res, next) { res.send(201, 'hello ' + req.body.name); return next(); }); server.on('restifyError', function(req, res, err, callback) { console.error(err.stack); res.send(err); callback(); }); server.get('/context', function(req, res, next) { const data = { timestamp: new Date(), method: req.method, query: req.query }; res.send(data); return next(); }); server.listen(8080, function() { console.log('%s listening at %s', server.name, server.url); });
By following this example, you can quickly set up a robust and reliable RESTful API service using Restify.
Hash: d2eefe0f20b1e0199415bf95aa5a3675b13c9fa4c124e5d59f7c6b6b4da8c2b2