Dev

By Carlos Santana on
Reading time: 5 minutes

Nodejs-Bv4YU.png

Express is the most popular Node.js framework and is really easy to install and to use it. In this post, I'll show you how to create a basic API using Express.

First, you need to install Node.js, I recommend you to read the article How to install and uninstall Node.js completely.

After you installed Node you have to install Express generator to create your first express application.

npm install -g express-generator

Then you can create your first application with the command:

express node-api

Once you run the command, you will see this:

NodeAPIExpress-h1IjK.png

Then follow the instructions to run the express application at http://localhost:3000.

cd node-api
npm install
npm start

You should see this view: 

ExpressApp-a90rx.png

ES5 to ES6

The generated code for the express application is ES5 that means is using old JS syntax like var, require, module.exports, etc. This is the default generated code:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
File: app.js

Let's migrate it to ES6:

// Dependencies
import createError from 'http-errors';
import express from 'express';
import path from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';

// Routes
import indexRouter from './routes/index';
import usersRouter from './routes/users';

// Express App
const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Routes
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// Listening port
app.listen(3000);
File: app.js

Now that we are listening directly the port 3000 in our code you can remove the bin/www directory, and then modify the start script in your package.json

"scripts": {
  "start": "node app.js"
}
File: package.json

If you try to run the application again using npm start you will get this error: 

UnexpectedTokenImport-GbJu0.png

The error is caused by the ES6 syntax which is not supported by Node directly. We need to install @babel/core, @babel/node, and @babel/preset-env in order to fix this problem:

npm install @babel/core @babel/node @babel/preset-env

Then create the file .babelrc and add this:

{
  "presets": ["@babel/preset-env"]
}
File: .babelrc

Now you have to change your start script in the package.json:

"scripts": {
  "start": "babel-node app.js"
}
File: package.json

You should be able to run the application without problems now. But now we have another issue, by default every time we made a change in our code we need to manually restart the server. Nodemon is a package that will help us to avoid this problem, and if we use it every time we made a change then automatically will restart the node server for us.

npm install nodemon

Then modify your start script:

"scripts": {
  "start": "nodemon app.js --exec babel-node"
}
File: package.json

Creating the API

As you know we want to create an API with Node, but our initial app.js file has a lot of things that we may not use, so let's clean up a little bit and then just use the packages needed for this purpose. This should be our new app.js: 

// Dependencies
import express from 'express';
import path from 'path';

// Controllers
import apiController from './controllers/api';

// Express Application
const app = express();

// Middlewares
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Routes
app.use('/api', apiController);

// Listening port
app.listen(3000);
File: app.js

The main change is that the routes are now controllers and we are executing our API Controller when we match the /api url. Our API Controller should be like this:

Only members can see all the codes
You can Login or Sign Up

File: controllers/api.js

You can test the API by hitting the endpoint: http://localhost:3000/api/blog/posts.

PostsResponse-S0Dlq.png

If you want to select a specific post then you can hit http://localhost:3000/api/blog/post/2.

SinglePost-76ERO.png

Finally, if you try to get a post id that does not exist then you will get this error:

PostNotFound-XqAsp.png

In the next post, I'll explain to you how we can implement MongoDB to our API, I hope this post was useful for you, don't forget to share it with your friends.

avatarLeave a comment

Your comment

Only members can comment. You can Login or Sign Up