Skip to content

What is REST

Adarsh Kumar Maurya edited this page Dec 18, 2018 · 2 revisions

What Is REST?

Introduction Welcome to RESTful Web Services with Node.js and Express. In this module we're going to talk about how to build a RESTful API with Node and Express. We'll start out by talking about what REST really is and then we'll setup a Node and Express environment so we can get started. We'll implement all of the REST verbs, get, put, post, patch, delete, and when you would use the different verbs. We'll wire everything up to MongoDB using Mongoose for our backend. We'll unit test with Mocha and Sinon.js, Sinon will be used for our mocking, and then we'll end with a conversation on hypermedia and why links in our APIs help our API consumers navigate our API.

What Is REST?

Before we can start building a RESTful API we need to have a good understanding of what REST really means. The term REST comes from a dissertation written by Roy Fielding back in 2000. In this dissertation he coins the term Representational State Transfer or ReST. In this chapter of the dissertation he begins to layout a series of constraints that should be in place whenever two systems talk to each other, so ultimately what REST is is just a series of rules in place for your server, so that everyone that uses your service understands what it does and how it works. Let's take a look at these constraints and see if we can't make sense of what he's talking about. The first constraint is the Client Server constraint. All that means is that you have a client and a server and the client sends a request to the server, the server sends a response back to the client. This should seem pretty straightforward to you, in fact, this is the way the web works, and chances are if you're watching this video you do some stuff in the web and this is how you understand most things to work. There's no tricks here it's just that, client sends a request, server sends a response, that's how that works. The next constraint is the constraint of the Stateless Server. As the load from the client increases on your server you start to add more servers to the mix and when that happens now you get into a situation where the server may contain some information about the client that doesn't transfer from one server to the other. In this constraint Roy Fielding suggests that you don't get into that situation. Ultimately the client sends a request to the server and it doesn't matter what server it goes to, so everything that the server's going to need to process this request should be included in that request, and then based on that request and based on all that information that's in the request it'll send a response to the server. If you find yourself on the server storing information about the request or about the client, then you're not writing a truly RESTful service. The next constraint is the constraint of caching, so ultimately as servers are sending responses back full of data, sometimes you're sending back data that doesn't change very often, so think about a list of clients or a list of book authors or something along those lines. That data's not going to change between now and 5 minutes from now the next time the client pulls that data, so this constraint says let the client know how long this data is good for, so that the client doesn't have to come back to the server for that data over and over again. We're not going to go too deep into this one in this course, but I just wanted to make sure you understood what that meant and how that works.

Uniform Interface

The last constraint we'll talk about is the constraint of the Uniform Interface. Basically what Roy Fielding's talking about here is when you're dealing with an interface for a RESTful service it will behave in a very specific way that is uniform from one service to the next, and in this he outlines four pieces to an interface that should always operate this way, the first one being the idea of resources. Whenever you're dealing with a RESTful service you'll be dealing with a resource or a series of resources and all that really means is you're dealing with nouns. Uniform Interfaces are built around things, not actions. Sometimes when you call a service it'll be authorize or login. Those are verbs. In ReST everything we're going to be dealing with is nouns, so for this project we're going to be working with books and authors. Both of these are the resources that each of our ReSt services will be dealing with. For example, dealing with a book, the URL will be HTTP://something/book. If we're dealing with authors it would be /author. That's the way a ReSt Service will be defined every time. The second piece of a uniform interface is contained within the HTTP verbs. The HTTP verbs that we use I our request will dictate the type of activity we're trying to do on the resource. For example, our HTTP Get will simply request data, so I'm just trying to get data, and it'll either return a list of objects or a specific object. The post is used to add data, so if I do post to a /book I'm going to add a new book. Delete will remove. Put is used to update, so if I would just want to update or replace a resource I use Put. Patch is coming more into favor now too for just updating a piece of our resource. Put updates the entire resource, patch will just update a piece of that resource. The last piece of the Uniform Interface is the acronym HATEOUS, which has to be the coolest acronym that we have in REST. HATEOS stands for Hypermedia as the Engine of Application State, which I know is not very descriptive at all. Basically all that means is that in each request will be a set of hyperlinks that you can use to navigate the API. It's just the API's way of letting you know what other actions you can take on this particular resource. Don't worry about that one too much right now, we will get into that later on in this course.

Setting up Our Environment

Now in order to get our environment started the first thing we have to do is download and install Node. You'll find that out on NodeJS.org. Click Install and it'll download a package or an installer for the system that you have. Go ahead and get that installed and then we'll get started. Once Node is installed we'll use Mode Package Manager to install all of the other things we're going to need for our project. Note the package manager is just a simple way to download and install packages from the internet. It's very similar to NuGet over on the .NET side. Now in order to get started with Node Package Manager the first thing we're going to do is an npm init and what npm init is going to do is gather some basic information about your project and setup a config file, so that it can save all of the packages that We're going to be using, so the first thing we'll do is give it a name, so we'll call our project BookAPI and everything else we'll just leave blank for right now. Now if you look over in our projects you'll now see we have a package.json file and that file basically just has all of that information we just entered. Now for the record I'm using a web storm for this demo. You can use any IDE you want to follow along, Sublime, Vim, Notepad, Visual Studio. Visual Studio has a Node plugin that you can download and install to get the Node syntax coloring too. The IDE doesn't really matter. I'm not going to be using anything specific to Webstorm in this demo even though there are some cool features. I'm going to intentionally not talk about those things. You can use whatever IDE you're comfortable with and get the most out of this course. Now that we have a package.json file the first package we have to install is Express. In order to install packages into our project we do an npm install, so in this case, npm install express. Now we'll do a --save and this'll tell npm to save a record of this over in the package.json. Now the reason we do this is so that when I check this into source control or I give this code to someone else I don't have to give them all of the packages. When they get my code they just do npm install and npm will look at this package.json file and see that it needs express. Then it will go and download Express on its own. Now this carrot right here basically just means when I do an npm install it'll go look for any version of Express that is compatible with 4.11.2, so if between now and the time you go install Express 4.11.3 has come out that's fine, it'll download and install that as long as it's deemed compatible. If version 5 comes out, if you have ^4.11.2 it'll only download 4.11.2, it won't go download version 5. Now that Express is installed let's go ahead and get started and set up just a basic web server using Express to do something very basic just so that you can see that your code works. We're going to create a new Javascript file called app.js. Now the first thing we have to do is create a reference to Express, so we'll do var express = require('express'). Now one quick thing to point out, notice how it doesn't know what require is. This is a webstorm specific thing, but if I right-click and go to Use Javascript Library, and then click Node.js Globals, now it starts to notice some of the node specific things. Alright, now that I have a reference to Express I can go ahead and get started. The first thing we're going to do is var app and create an instance of Express that we can use to start running our stuff, so var app = express, but then we're going to execute that. The second thing we need in order to setup our server is to setup a port, so we'll do var port, and then there's two different ways you can get the port. The first way I'm going to show you is using an environment process, so we'll do process.env.PORT and if that's not there we'll hand it a port, so we'll say port 3000. Now all this does is it looks for this in the environment and if that's not there than it gives it the port 300, so for right now, since we don't have an environment setup it'll just be 3000. Now the next thing we want to do is setup a handler for our route and there's a couple ways to do this. I'm going to show you the simplest way for right now and we'll use something a little more complicated here in a minute, but to start we'll do app.get and the first parameter is just going to do a slash, which basically means just the root of your site. The second parameter is going to be a callback function. Anytime anything hits that root slash this function will be executed and Express is going to pass two variables, req and res. Req is the request that was sent by the client, res is the response that we're going to send back. In this case we're just going to send back a simple little welcome message, something like welcome to my API. Now that we have a variable for port, we have app, we have a route, the last thing we need is to actually have Express start listening on the port, so we'll do an app.listen with the port number, and then a callback function just to let us know that the app started listening. In this case let's just do a console.log and say that we're running on PORT with our port number. Alright, now that that's done let's fire this up by typing node app.js and if we've done everything right we get a message saying Running on PORT 3000 and we should be able to go to localhost and you see we get an error, so real quick let's jump back over. Notice right here we typed req, so instead we want to do res for the response not the request, and then since I changed this code I have to stop the server and start it back up again. Now I hit refresh and you'll see welcome to my API.

Getting Gulp Set Up

Now as you can probably imagine having to stop and restart our server every time we make a change is going to be fairly tedious over the course of this course, so we're going to use Gulp to manage that process for us. Now we're not going to get too deep into Gulp in this course, a fantastic Gulp course was just released recently on Pluralsight by John Papa and I would highly recommend you go watch that course, but here we're going to do just enough to get our node server up and running, so that it'll watch for file changes and automatically restart. We'll stop this and we're going to install Gulp and we're going to have to do two installs here, so the first install is just going to be our npm install gulp --save. Now again, we do the --save, so that when you come over here to your package.json now you see Gulp as a dependency. Now I want to be able to use Gulp from the command line because I'm going to use Gulp to run my service instead of using Node, so I have to install Gulp with a -g tag, so that I have access to it from the command line. Now when Gulp runs it's going to look for a file called gulpfile.js, so let's create that file. Now the first thing you have to do for Gulp is create a reference to Gulp. Let's do var gulp = require('gulp'). Now gulp is just the task runner, so the plugin we need in order to do what we're looking to do is a plugin called nodemon, so let's do an npm install gulp-nodemon. Now let's create a reference to that too. Now for Gulp all we have to do is tell it we have a task and we'll call it the default task for right now, and then use that task to execute our nodemon plug, so we'll do gulp task and we'll call it default, and then well pass in a function that'll setup nodemon. Now nodemon's going to take a JSON object to configure itself, so the first thing it needs to know is what it's going to run, so I'll send it script and the script name is app.js. Now it also needs to know what to watch for. We want it to watch for js extensions, so we'll tell it ext: 'js'. Now remember over in our app.js we were saying sometimes the environment will contain a port. Nodemon actually will let us set that up, so we're going to setup an environment with a port equal to 8000 and I'm setting it to something different just so you can tell where it's coming from. Now every time I install a node module or something like that I don't want it to get confused, so we're going to ignore everything under node modules. Now that's it for nodemon, but we want to let ourselves know that it's restarted, so we'll do a .on('restart') just saying hey, when you restart let's execute this function and we're just going to write something out to the log that says we've restarted (Typing). Now that this Gulp file is setup we should be able to come over here and type gulp. Now notice we are now running on port 8000 instead of 3000, so we are successfully pulling our --- port out of the environment and using that instead of the hard-coded 3000, so let's just double check and make sure everything's working. We've got to change this to --- 8000 and there we are, welcome to my API. Now let's change something (Typing) and when that saves you'll see we restarted, so now as we make changes Gulp will see that we've made changes and just automatically restart our server, so we don't have to go through the process of killing the server and starting it up again.

Summary

In this module we started learning how to build a RESTful API with Node and Express. We're not done yet, in fact we've barely even gotten started, but what we have done is we've talked about what REST is, so we understand the constraints, so we understand why we do things the way that we're going to do them. We setup our Node and our Express environment, got things going a simple HTTP response just so we have the pieces in place so we can get started, and we used Gulp to run our server. In this next module we'll build off of what we have and we'll start to build out the HTTP Get verbs and hook everything up to MongoDB.

Clone this wiki locally