Recently I have been working with some Web API and I am forced down the path of Java. So far, I must say that I am confident in this assertion: creating a Web API is much simpler in Node.
It's not that I don't like Java but I am more familiar with Javascript and Node seems to be more suited to the task of Web APIs. This isn't to say it is the best and Java certainly has its own advantages. For instance, Java is more powerful. As a side note, I have made Web APIs in C#.NET and I am pretty impressed with their implementation.
All that aside, I wanted to show a quick how to on making a Web API in Node.
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
app.post('/api/v1/:resource', function(req, res) {
let resource = req.params.resource,
body = req.body;
// do something with the JSON in the body
res.sendStatus(200);
});
app.get('/api/v1/:resource', function(req, res) {
let resource = req.params.resource,
body = getData(); //ficticious method for getting the resource
res.send(JSON.stringify(body));
});
app.listen(8888);
So there is a very simple REST interface using Node+Express. You need to install Express, bodyParser, and cors for this to work but that isn't too difficult.
npm install --save express cors bodyParser
bodyParser allows for receiving JSON from the POST body and cors is used to allow cross origin requests. These are not necessary for a simple Web API but you may find yourself needing them.
app.post tells express to run the provided function whenever the url is POSTed to. In this instance,
:resource will be whatever is put in that location of the URL.
http://domain/api/v1/users maps
:resource to
users
app.get works similarly but instead of changing the data, it returns it in the body of the response.
Finally,
app.listen tells the server to listen for requests on the specified port.
Start it up using
npm start and you are ready to go!
No comments:
Post a Comment