Created
June 2, 2016 14:02
-
-
Save hai5nguy/343e65b97a6e2cb6ec23ff71da9fa416 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
Creating a simple REST API server | |
================================== | |
This is the simplest way to create a RESTful API server with nodejs. We will create a node server that will use the express module. Then we will define one route/endpoint for the server to act upon. This route will return json data, the prefer data format for RESTful APIs. But note that other data format can be returned too, rest does not enforce this. | |
Steps: | |
1. Create a folder to hold our server/project. | |
2. Create an index.js file as the starting point for our node app/server | |
3. Add package.json via npm init, you can hit enter for everything and fill them out later | |
4. Add express, run | |
npm install --save express | |
5. Code the following into index.js | |
//////////////////////////////////////////////////////////////////// | |
// import express (or sometimes called "requiring in") | |
// require('express') returns a function, that's the way the module creator made it | |
var express = require('express') | |
//create the app by calling the express() function | |
var app = express() | |
//define our first route/endpoint. In a restful api, a route is called an "endpoint", in a web server that serves html/js/css, it is called a route. Express does not distinguish the two. | |
app.get('/getstuff', function (req, res) { | |
var data = { stuff: 'this is stuff, stuff can be from another node module, it can be from a database, it can be from another api, it can be static like so' } | |
res.json(data) | |
}) | |
//start the server aka "listening", hit control+c to stop the server | |
app.listen(5000, function () { | |
console.log('api server online.') //just to let us know it's running | |
}) | |
//////////////////////////////////////////////////////////////////// | |
6. Save, and run node index.js (node index also works) | |
7. Browse to http://localhost:5000/getstuff | |
8. Note the data returned. Note that if you go to http://localhost:5000/, it doesn't return any data because we have not defined that route/endpoint | |
9. The chrome devtools network tab also gives a raw view of the data and the request and response. | |
10. That's it, you've created your first REST API! | |
Final thoughts. You can imagine in the real work, there would be hundreds of endpoints. Also we only implemented a GET HTTP method, which is going from server to client. Ohter methods include POST, PATCH, PUT, DELETE, OPTIONS which you can learn later, but they are all cousins to GET. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment