Introduction to Restify
Restify is a popular Node.js framework used for building RESTful web services. It is designed to optimize performance, manage appropriate HTTP methods and status codes, and support versioning and caching effectively.
Basic Server Setup
Create a basic server using Restify.
const restify = require('restify'); const server = restify.createServer(); server.get('/hello', (req, res, next) => { res.send('Hello World'); next(); }); server.listen(8080, () => { console.log('%s listening at %s', server.name, server.url); });
Parsing Request Body
Restify supports several plugins to parse the body of incoming requests.
server.use(restify.plugins.bodyParser()); server.use(restify.plugins.queryParser());
Handling Routes
Add various HTTP methods like GET, POST, PUT, and DELETE.
server.get('/data', (req, res, next) => { res.send({data: 'GET data'}); next(); }); server.post('/data', (req, res, next) => { res.send({data: 'POST data'}); next(); }); server.put('/data', (req, res, next) => { res.send({data: 'PUT data'}); next(); }); server.del('/data', (req, res, next) => { res.send({data: 'DELETE data'}); next(); });
Middleware
Use middleware for authentication or logging.
server.use((req, res, next) => { console.log('Request received at:', Date.now()); return next(); }); server.use((req, res, next) => { if (!req.headers.authorization) { res.send(401, 'Unauthorized'); return next(false); } return next(); });
Error Handling
Custom error handling in Restify.
server.on('restifyError', (req, res, err, callback) => { console.error(err); res.send(err); return callback(); });
Example Application
A simple app using Restify.
const restify = require('restify'); const server = restify.createServer(); server.use(restify.plugins.bodyParser()); server.use(restify.plugins.queryParser()); server.get('/ping', (req, res, next) => { res.send('pong'); next(); }); server.post('/echo', (req, res, next) => { res.send(req.body); next(); }); server.listen(8080, () => { console.log('%s listening at %s', server.name, server.url); });
By following this guide, you can build efficient and scalable RESTful web services with Restify.
Hash: d2eefe0f20b1e0199415bf95aa5a3675b13c9fa4c124e5d59f7c6b6b4da8c2b2