Journey into React Part 5: Creating a RESTful API with Express

Datetime:2016-08-23 01:55:58          Topic: React  REST           Share

We're going to be changing gears a bit here with Part 5 of our React.js tutorial and focus now on the back-end of our application. This section will center on creating an express server that uses cors and body-parser to send JSON responses to our clients. It'll do this when they send a "get" request to our hello world API. We'll also create our first controller and first API route to handle these requests!

Part 5 is a little unique in that it does not rely on the previous 4 tutorials, and our server stands completely independent of what we'vepreviously worked on. However, the API that we'll be starting today will be the one that'll connect with our client application in the future parts of this series. This API will handle our server side authentication and database communication in the future.

If you're just joining me for this part, then welcome aboard! But, if you want to start creating your own full-stack React applications then I recommend you head over toPart 1 of this Journey into React. Now, let's get started!

Required dependencies check-up

There're a few things that are required (and also very convenient to have) that we'll be using with this tutorial, so let's make sure you have them installed. If not, we'll get that taken care of - no problem. We need Node of course, and most importantly, so do a quick check in your console:

node -v

This should return your version number, or tell you that it's simply not there at all. If you get the latter response use NPM to install node globally to your machine:

npm install --g node

After a moment that should be taken care of, test again to make sure it installed successfully. Next, repeat this process for nodemon , a handy tool we'll use to automatically restart our server anytime we make a change to it:

nodemon -v  
npm install --g nodemon //if not present

Restructure our directories

If you've been following along through this tutorial from the beginning you will want to follow this section. If you only care about getting your express server to work, you can skip this part.

Since we'll be creating a full-stack application that needs both a server and a client to work we need to reorganize our project directory so that it's a bit cleaner and can accommodate this. Open up your "journey-into-react" project directory (or in your Atom.io editor) and create an empty folder called "client".

Next, on your console, you want to uninstall the dependencies from the client-side application. It's easier to do it from the console as often the file paths are too long for Windows to be able to simply "delete" them. You could also try to move the node_modules directory into the "client" one we just made, but I've had issues with that in the past. So, copy this into your console and hit enter:

npm uninstall lemonade-grid react react-dom react-router babel-core babel-loader babel-plugin-add-module-exports babel-plugin-react-html-attrs babel-plugin-transform-class-properties babel-plugin-transform-decorators-legacy babel-preset-es2015 babel-preset-react babel-preset-stage-0 css-loader extract-text-webpack-plugin node-sass sass-loader style-loader webpack webpack-dev-server

That's the hardest part, I promise. Next, we want to move our src , index.html , package.json and webpack.config.js into the "client" directory as well, then we're all set. You will need to cd into the client and run npm install again to use your application in future.

Create a new directory in your 'journey-into-react' project folder called "server" and let's get coding!

Initialize our project and get the basics installed

Much like we did in the first part of this tutorial (ages ago!) we need to run npm init and follow the prompts on screen to get our package.json file created. Next, we install the dependencies that we need:

npm install --save body-parser cors express

Make sure you add the --save so that it adds these dependencies to your package.json file. Open up your package.json file and under "scripts" we want to add in a custom run script to save us some time, and automatically start our server with nodemon :

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon index.js"
  },

The heart of our server

Now we need to get our server running. We use express to do this. We'll also be wiring up the other dependencies you saw, body-parser and cors . We'll learn about this a little bit further down.

Create the file index.js in the server root directory, and begin "importing" the dependencies we need. We set them to constants here, as opposed to the import command we use in our React app.

const express = require('express'),  
      bodyParser = require('body-parser'),
      cors = require('cors'),
      app = express();

var port = 3000;

Below this we want to initialize our server, defining what we want our "app" to use to run our API.

app.use(bodyParser.urlencoded({ extended: false }));  
app.use(bodyParser.json());  
app.use(cors());

Lastly, we can start our server by simply adding:

app.listen(port);  
console.log('Your server is running on port ' + port + '.');

I've added a console log there so you can verify that it's working. Go ahead and turn on your server with npm run dev (the custom run script we wrote). With any luck, you'll see a little message on your console! Press ctrl-c twice to shut off your server.

Creating our first controller and function

Now that we know the server is working, let's start making it do stuff. Create a new folder in the server root directory named "controllers". Here you will store all the functions that will be called when your client-side application makes a request to your API. We want to start with an easy one, so make a controller named _our-controller.js . We'll likely change the name later, but for the sake of this tutorial let's roll with this.

Ideally, you'll organize your controllers into different files like this: _authController, _clientController, _communicationController, etc. This keeps your project clean and easy to error handle.

As of now, _ourController doesn't require any dependencies, so we get to jump right into making our hello world function. Every function that we write is going to take three parameters req , res , and next . Requests , Responses , and next are always used when making HTTP calls/requests. Since this simple function isn't going to take any values we only need to worry about returning a response when it's called.

exports.helloworld = function(req, res, next) {  
  res.status(200).json({
    message: "Hello world!"
  })
}

It was starting to sound like a lot, but really it's quite simple. We're exporting a function called helloworld , taking an empty req uest, and we're res ponding with the message "hello world".

You'll remember we installed and included body-parser in our index.js file. Our message is a JSON object and it's the use of body-parser that allows our API to do that. This, and cors will become increasingly important as our API sends entire objects of information to our clients.

Using a route to point to our hello world function

The last key part we need to add to our server is a router file. Create one titled router.js in the server root directory. We need express and our controller in here so import those:

const express = require('express');  
const _ourController = require('./controllers/_our-controller');

And now we want to export the routes that we create to our app . This module is going to require express.Router() and will create the routes with the base URL /api .

module.exports = function(app) {  
  const apiRoutes = express.Router();

  //routes will go here

  app.use('/api', apiRoutes);
}

Now let's write up our route. It's going to use the apiRoutes we defined above, and we want to use a get method. We'll talk more about the different HTTP methods in a later tutorial. We need to define a path for our route, and then tell it what function to call when that path is accessed:

apiRoutes.get('/helloworld', _ourController.helloworld);

Once again, it sounds much more difficult than it is. Now that this is complete, we can save and move on to wiring it all together.

Wiring in our router and testing it

Let's open up our index.js file again and add two more small things. We need to import the route we just made so add that near the top:

const router = require('./router');

And we want the router to take our App as a parameter, so just below app.use(cors()); add in:

router(app);

We should be all set now to take our API out for a spin. We can do that with the help of a handy free tool Postman . Get that installed and your free account setup, then open it up.

Once Postman is open and you're logged in, you'll see at the top the option to change your HTTP method and enter a URL. Set the method to "GET" and type in your routes URL: http://localhost:3000/api/helloworld . You should see a neat little "Hello World!" pop up below in the body box.

You've done it! You have made your first API and successfully made a call to it! This is going to open the door to all the amazing things we have planned for our application. Using very similar methods you'll be able to push information to a mongoose database, and send information back to your clients. You can even use this API structure to make calls to third-party API's like Facebook and Twitter.

That's all for today, if you have any questions or comments please leave them below! I value your feedback and look forward to talking with you. Until later, happy coding!





About List