Build a REST API with Node.js, Express, and MySQL (ok)

Không biết sao kiểu 1 này không dùng được dạng string :(

curl -i -X POST -H 'Accept: application/json' \
  -H 'Content-type: application/json' http://localhost:3000/programming-languages \
  --data '{"name": "abcd", "released_year": "2011", "githut_rank": "13", "pypl_rank": "20", "tiobe_rank": "25"}'

Dùng dạng số thì được ví dụ:

Còn ví dụ sau thì dùng được tất cả các loại :)

curl --location --request POST 'http://localhost:3000/programming-languages' \
--header 'Accept: application/json' \
--header 'Content-type: application/x-www-form-urlencoded' \
--data-urlencode 'name="abc123"' \
--data-urlencode 'released_year=13' \
--data-urlencode 'githut_rank=14' \
--data-urlencode 'pypl_rank=15' \
--data-urlencode 'tiobe_rank=16'

Nhưng không hiểu sao PUT lại được :)

 curl -i -X PUT -H 'Accept: application/json' \
    -H 'Content-type: application/json' http://localhost:3000/programming-languages/17 \
    --data '{"name":"111111ab", "released_year": 2011, "githut_rank": 12, "pypl_rank": 20, "tiobe_rank": 25}'

C:\Users\Administrator\OneDrive\Desktop\programming-languages-api\package.json

{
  "name": "programming-languages-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1",
    "mysql2": "^2.3.3"
  }
}
-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 12, 2022 at 06:26 AM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.28

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `programming_languages`
--

-- --------------------------------------------------------

--
-- Table structure for table `programming_languages`
--

CREATE TABLE `programming_languages` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `released_year` int(11) NOT NULL,
  `githut_rank` int(11) DEFAULT NULL,
  `pypl_rank` int(11) DEFAULT NULL,
  `tiobe_rank` int(11) DEFAULT NULL,
  `created_at` datetime NOT NULL DEFAULT current_timestamp(),
  `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `programming_languages`
--

INSERT INTO `programming_languages` (`id`, `name`, `released_year`, `githut_rank`, `pypl_rank`, `tiobe_rank`, `created_at`, `updated_at`) VALUES
(1, 'JavaScript', 1995, 1, 3, 7, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(2, 'Python', 1991, 2, 1, 3, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(3, 'Java', 1995, 3, 2, 2, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(4, 'TypeScript', 2012, 7, 10, 42, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(5, 'C#', 2000, 9, 4, 5, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(6, 'PHP', 1995, 8, 6, 8, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(7, 'C++', 1985, 5, 5, 4, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(8, 'C', 1972, 10, 5, 1, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(9, 'Ruby', 1995, 6, 15, 15, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(10, 'R', 1993, 33, 7, 9, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(11, 'Objective-C', 1984, 18, 8, 18, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(12, 'Swift', 2015, 16, 9, 13, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(13, 'Kotlin', 2011, 15, 12, 40, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(14, 'Go', 2009, 4, 13, 14, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(15, 'Rust', 2010, 14, 16, 26, '2022-06-12 11:14:57', '2022-06-12 11:14:57'),
(16, 'Scala', 2004, 11, 17, 34, '2022-06-12 11:14:57', '2022-06-12 11:14:57');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `programming_languages`
--
ALTER TABLE `programming_languages`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `idx_name_unique` (`name`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `programming_languages`
--
ALTER TABLE `programming_languages`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

C:\Users\Administrator\OneDrive\Desktop\programming-languages-api\config.js

const config = {
  db: {
    /* don't expose password or any sensitive info, done only for demo */
    host: "localhost",
    user: "root",
    password: "",
    database: "programming_languages",
  },
  listPerPage: 10,
};
module.exports = config;

C:\Users\Administrator\OneDrive\Desktop\programming-languages-api\helper.js

function getOffset(currentPage = 1, listPerPage) {
  return (currentPage - 1) * [listPerPage];
}
function emptyOrRows(rows) {
  if (!rows) {
    return [];
  }
  return rows;
}
module.exports = {
  getOffset,
  emptyOrRows
}

C:\Users\Administrator\OneDrive\Desktop\programming-languages-api\services\db.js

const mysql = require('mysql2/promise');
const config = require('../config');
async function query(sql, params) {
  const connection = await mysql.createConnection(config.db);
  const [results, ] = await connection.execute(sql, params);
  return results;
}
module.exports = {
  query
}

C:\Users\Administrator\OneDrive\Desktop\programming-languages-api\services\programmingLanguages.js

const db = require('./db');
const helper = require('../helper');
const config = require('../config');
async function getMultiple(page = 1) {
  const offset = helper.getOffset(page, config.listPerPage);
  const rows = await db.query(
    `SELECT id, name, released_year, githut_rank, pypl_rank, tiobe_rank 
    FROM programming_languages LIMIT ${offset},${config.listPerPage}`
  );
  const data = helper.emptyOrRows(rows);
  const meta = { page };
  return {
    data,
    meta
  }
}
async function create(programmingLanguage) {
  const result = await db.query(
    `INSERT INTO programming_languages 
    (name, released_year, githut_rank, pypl_rank, tiobe_rank) 
    VALUES 
    (${programmingLanguage.name}, ${programmingLanguage.released_year}, ${programmingLanguage.githut_rank}, ${programmingLanguage.pypl_rank}, ${programmingLanguage.tiobe_rank})`
  );
  let message = 'Error in creating programming language';
  if (result.affectedRows) {
    message = 'Programming language created successfully';
  }
  return { message };
}
async function update(id, programmingLanguage) {
  const result = await db.query(
    `UPDATE programming_languages 
    SET name="${programmingLanguage.name}", released_year=${programmingLanguage.released_year}, githut_rank=${programmingLanguage.githut_rank}, 
    pypl_rank=${programmingLanguage.pypl_rank}, tiobe_rank=${programmingLanguage.tiobe_rank} 
    WHERE id=${id}`
  );
  let message = 'Error in updating programming language';
  if (result.affectedRows) {
    message = 'Programming language updated successfully';
  }
  return { message };
}
async function remove(id) {
  const result = await db.query(
    `DELETE FROM programming_languages WHERE id=${id}`
  );
  let message = 'Error in deleting programming language';
  if (result.affectedRows) {
    message = 'Programming language deleted successfully';
  }
  return { message };
}
module.exports = {
  getMultiple,
  create,
  update,
  remove
}

C:\Users\Administrator\OneDrive\Desktop\programming-languages-api\routes\programmingLanguages.js

const express = require('express');
const router = express.Router();
const programmingLanguages = require('../services/programmingLanguages');
/* GET programming languages. */
router.get('/', async function(req, res, next) {
  try {
    res.json(await programmingLanguages.getMultiple(req.query.page));
  } catch (err) {
    console.error(`Error while getting programming languages `, err.message);
    next(err);
  }
});
/* POST programming language */
router.post('/', async function(req, res, next) {
  try {
    res.json(await programmingLanguages.create(req.body));
  } catch (err) {
    console.error(`Error while creating programming language`, err.message);
    next(err);
  }
});
/* PUT programming language */
router.put('/:id', async function(req, res, next) {
  try {
    res.json(await programmingLanguages.update(req.params.id, req.body));
  } catch (err) {
    console.error(`Error while updating programming language`, err.message);
    next(err);
  }
});
/* DELETE programming language */
router.delete('/:id', async function(req, res, next) {
  try {
    res.json(await programmingLanguages.remove(req.params.id));
  } catch (err) {
    console.error(`Error while deleting programming language`, err.message);
    next(err);
  }
});
module.exports = router;

Build a REST API with Node.js, Express, and MySQL

January 18, 2022 10 min read

Editor’s note: This tutorial was last updated 1 February 2022 to replace tools that had become outdated.

Generally, Node.js is coupled with MongoDB and other NoSQL databases, but Node.js performs well with relational databases like MySQL, too. If you want to write a new microservice with Node.js for an existing database, it’s highly likely that you’ll use MySQL, one of the world’s most popular open-source databases.

In this tutorial, we’ll learn how to build a REST API using MySQL as our database and Node.js as our language. We’ll also use the Express.js framework to make our task easier. Our example REST API will track the most popular programming languages.

Prerequisites

To follow along with this article, you should have the following:

  • Understanding of how MySQL and relational databases work in general

  • Basic knowledge of Node.js and Express.js

  • Understanding of what REST (representational state transfer) APIs are and how they function

  • Knowledge of what CRUD (create, read, update, delete) is and how it relates to the HTTP methods GET, POST, PUT, and DELETE

The code in this tutorial is performed on a Mac with Node 14 LTS installed. If you want, you can try to use Node.js, Docker, and Docker Compose to improve developer experience. You can also access the full code at the GitHub repository. Let’s get started!

Table of contents

What is MySQL?

MySQL is one of the most popular databases in the world, if not the most popular. Per the 2020 Stack Overflow survey, MySQL was the most-loved database, with more than 55 percent of respondents using it. The community edition is freely available, supported by a large and active community.

MySQL is a feature-packed relational database first released in 1995. MySQL runs on all major operating systems like, Linux, Windows, and macOS. Because of its features and its cost-effectiveness, MySQL is used by big enterprises and new startups alike.

For our example REST API, we’ll use a free MySQL service instead of setting up a local MySQL server. To host our testing MySQL database, we’ll use db4free.net.

Register on db4free.net

To get your free MySQL 8.0 database up and running, you can register on db4free.net. First, go to the db4free signup page, then fill out the required details by choosing your database name and username:

Click on Signup and you should receive a confirmation email. Confirm your account by clicking on the link in the email. Next, on the sidebar, click on phpMyAdmin. In the phpMyAdmin login, enter the username and password you chose and click Go:

Create the programming languages table

Now, we have an empty database. Let’s add the programming_languages table. First, click on the database name on the left; for me, it was restapitest123. Then, click SQL on the top menu, which is the second link after Structure, and put the following code for CREATE TABLE in the text area:

CREATE TABLE `programming_languages`
(
  `id`            INT(11) NOT NULL auto_increment ,
  `name`          VARCHAR(255) NOT NULL ,
  `released_year` INT NOT NULL ,
  `githut_rank`   INT NULL ,
  `pypl_rank`     INT NULL ,
  `tiobe_rank`    INT NULL ,
  `created_at`    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
  `updated_at`    DATETIME on UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
  PRIMARY KEY (`id`),
  UNIQUE `idx_name_unique` (`name`(255))
)
engine = innodb charset=utf8mb4 COLLATE utf8mb4_general_ci;

Click the Go button, as below:

The code will come back with a green check box and a message along the lines of MySQL returned an empty result set (i.e. zero rows).

With that, we’ve created a table called programming_languages with eight columns and a primary key called id, which is an internet and auto-increment. The name column is unique, and we also added the released_year for the programming language. We have three columns to input the rank of the programming language, sourced from the following resources:

The created_at and updated_at columns store dates to keep a track of when the rows were created and updated.

Add demo rows for programming languages

Next, we’ll add 16 popular programming languages to our programming_languages table. Click the same SQL link on the top of the page and copy and paste the code below:

INSERT INTO programming_languages(id,name,released_year,githut_rank,pypl_rank,tiobe_rank) 
VALUES 
(1,'JavaScript',1995,1,3,7),
(2,'Python',1991,2,1,3),
(3,'Java',1995,3,2,2),
(4,'TypeScript',2012,7,10,42),
(5,'C#',2000,9,4,5),
(6,'PHP',1995,8,6,8),
(7,'C++',1985,5,5,4),
(8,'C',1972,10,5,1),
(9,'Ruby',1995,6,15,15),
(10,'R',1993,33,7,9),
(11,'Objective-C',1984,18,8,18),
(12,'Swift',2015,16,9,13),
(13,'Kotlin',2011,15,12,40),
(14,'Go',2009,4,13,14),
(15,'Rust',2010,14,16,26),
(16,'Scala',2004,11,17,34);

You should receive a message that reads something like “16 rows inserted”.

The data collected from our three sources is collected and added to the table in bulk by the INSERT statement, creating 16 rows, one for each programming language. We’ll return to this later when we fetch data for the GET API endpoint.

If we click on the programming_languages table, visible on the left, we’ll see the rows that we just added:

Next, we’ll set up Express.js for our REST API with Node.js and MySQL.

Setting up Express.js for our REST API

To set up a Node.js app with an Express.js server, we’ll first create a directory for our project to reside in:

mkdir programming-languages-api && cd programming-languages-api

Then, we can create a package.json file with npm init -y as follows:

{
  "name": "programming-languages-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

To install Express, we’ll run npm i express, adding Express as a dependency in the package.json file.Next, we’ll create a slim server in the index.js file. It will print an ok message on the main path /:

const express = require("express");
const app = express();
const port = 3000;
app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);
app.get("/", (req, res) => {
  res.json({ message: "ok" });
});
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

There are a few important things to note in the code above. For one, we’ll using the built-in Express JSON parser middleware to parse JSON in the next steps. We’ll also utilize the express.urlencoded() middleware to parse the URL encoded body.

If the PORT is not provided as an environment variable, our app will run on port 3000. We can run the server with node index.js and hit http://localhost:3000 to see {message: "ok"} as the output.

REST API project structure

We’ll structure our project in the following manner to arrange our files logically in folders:

config.js will contain configuration for information like the database credentials and the rows we want to show per page when we paginate results. helper.js is the home for any helper functions, like calculating offset for pagination.

The routes/programmingLanguages.js file will act as the glue between the URI and the corresponding function in the services/programmingLanguages.js service. The services folder will house all our services. One of them is db.js, which we use to talk with the MySQL database.

Another service is programmingLanguages.js, which will have methods like getMultiple, create, etc. to get and create the programming language resource. Basic mapping of the URI and the related service function will look like the code below:

GET /programming-languages → getMultiple()
POST /programming-languages → create()
PUT /programming-languages/:id → update()
DELETE /programming-languages/:id → remove()

Now, let’s code our GET programming languages API with pagination.

To create our GET programming languages API, we’ll need to link our Node.js server with MySQL. To do so, we’ll use the mysql2 package from npm, which we can install with the npm i mysql2 command on the project root.

Next, we’ll create the config file on the root of the project with the following contents:

const config = {
  db: {
    /* don't expose password or any sensitive info, done only for demo */
    host: "db4free.net",
    user: "restapitest123",
    password: "restapitest123",
    database: "restapitest123",
  },
  listPerPage: 10,
};
module.exports = config;

Consequently, we’ll create the helper.js file with the code below:

function getOffset(currentPage = 1, listPerPage) {
  return (currentPage - 1) * [listPerPage];
}

function emptyOrRows(rows) {
  if (!rows) {
    return [];
  }
  return rows;
}

module.exports = {
  getOffset,
  emptyOrRows
}

For the fun part, we’ll add the route and link it to the services. First, we’ll connect to the database and enable running queries on the database in the services/db.js file:

const mysql = require('mysql2/promise');
const config = require('../config');

async function query(sql, params) {
  const connection = await mysql.createConnection(config.db);
  const [results, ] = await connection.execute(sql, params);

  return results;
}

module.exports = {
  query
}

Now, we’ll write up the services/programmingLanguage.js file that acts as the bridge between the route and the database:

const db = require('./db');
const helper = require('../helper');
const config = require('../config');

async function getMultiple(page = 1){
  const offset = helper.getOffset(page, config.listPerPage);
  const rows = await db.query(
    `SELECT id, name, released_year, githut_rank, pypl_rank, tiobe_rank 
    FROM programming_languages LIMIT ${offset},${config.listPerPage}`
  );
  const data = helper.emptyOrRows(rows);
  const meta = {page};

  return {
    data,
    meta
  }
}

module.exports = {
  getMultiple
}

After that, we’ll create the routes file in routes/programmingLanguages.js, which looks like the following:

const express = require('express');
const router = express.Router();
const programmingLanguages = require('../services/programmingLanguages');

/* GET programming languages. */
router.get('/', async function(req, res, next) {
  try {
    res.json(await programmingLanguages.getMultiple(req.query.page));
  } catch (err) {
    console.error(`Error while getting programming languages `, err.message);
    next(err);
  }
});

module.exports = router;

For the final piece of our GET endpoint, we need to wire up the route in the index.js file as follows:

const express = require("express");
const app = express();
const port = 3000;
const programmingLanguagesRouter = require("./routes/programmingLanguages");
app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);
app.get("/", (req, res) => {
  res.json({ message: "ok" });
});
app.use("/programming-languages", programmingLanguagesRouter);
/* Error handler middleware */
app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  console.error(err.message, err.stack);
  res.status(statusCode).json({ message: err.message });
  return;
});
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

We made two important changes in our entrypoint index.js file. For one, we added the code below:

const programmingLanguagesRouter = require('./routes/programmingLanguages');

Secondly, we link up the /programming-languages route to the router we just created as follows:

app.use('/programming-languages', programmingLanguagesRouter);

We’ve also added an error handler middleware to handle any errors and provide a proper status code and message.

After adding the GET endpoint, when we run our app again with node index.js and hit the browser with http://localhost:3000/programming-languages, we’ll see an output like the following:

Depending on the extensions you have installed on your browser, your output might look a little different.

Note that we’ve already implemented pagination for our GET API, which is possible because of the getOffset function in helper.js and the way we run the SELECT query in services/programmingLanguage.js. Try http://localhost:3000/programming-languages?page=2 to see languages 11–16.

POST a new programming language

Our POST API will allow us to create a new programming language in our table.

To create a POST programming language API in the /programming-languages endpoint, we’ll add code to the service and the routes files. In the service method, we’ll get the name, the release year, and other ranks from the request body, then insert them into the programming_languages table.

Append the following code to the services/programmingLanguages.js file:

async function create(programmingLanguage){
  const result = await db.query(
    `INSERT INTO programming_languages 
    (name, released_year, githut_rank, pypl_rank, tiobe_rank) 
    VALUES 
    (${programmingLanguage.name}, ${programmingLanguage.released_year}, ${programmingLanguage.githut_rank}, ${programmingLanguage.pypl_rank}, ${programmingLanguage.tiobe_rank})`
  );

  let message = 'Error in creating programming language';

  if (result.affectedRows) {
    message = 'Programming language created successfully';
  }

  return {message};
}

Make sure you export the following function as well:

module.exports = {
  getMultiple,
  create
}

For the function above to be accessible, we need to add a route to link it up in the routes/programmingLanguages.js file as follows:

/* POST programming language */
router.post('/', async function(req, res, next) {
  try {
    res.json(await programmingLanguages.create(req.body));
  } catch (err) {
    console.error(`Error while creating programming language`, err.message);
    next(err);
  }
});

PUT to update an existing programming language

To update an existing programming language, we’ll use the /programming-languages/:id endpoint, where we’ll get the data to update the language. To update a programming language, we’ll run the UPDATE query based on the data we got in the request.

PUT is an idempotent action, meaning if the same call is made over and over again, it will produce the exact same results. To enable updating existing records, we’ll add the following code to the programming language service:

async function update(id, programmingLanguage){
  const result = await db.query(
    `UPDATE programming_languages 
    SET name="${programmingLanguage.name}", released_year=${programmingLanguage.released_year}, githut_rank=${programmingLanguage.githut_rank}, 
    pypl_rank=${programmingLanguage.pypl_rank}, tiobe_rank=${programmingLanguage.tiobe_rank} 
    WHERE id=${id}` 
  );

  let message = 'Error in updating programming language';

  if (result.affectedRows) {
    message = 'Programming language updated successfully';
  }

  return {message};
}

Make sure you export this function as well as we did before:

module.exports = {
  getMultiple,
  create,
  update,
};

To wire up the code with the PUT endpoint, we’ll add the code below to the programming languages route file, just above module.exports = router;:

/* PUT programming language */
router.put('/:id', async function(req, res, next) {
  try {
    res.json(await programmingLanguages.update(req.params.id, req.body));
  } catch (err) {
    console.error(`Error while updating programming language`, err.message);
    next(err);
  }
});

Now, we have the ability to update any existing programming language. For instance, we can update a language’s name if we see a typo.

DELETE a programming language

We’ll use the /programming-languages/:id path with the HTTP DELETE method to add the functionality to delete a programming language. Go ahead and run the code below:

async function remove(id){
  const result = await db.query(
    `DELETE FROM programming_languages WHERE id=${id}`
  );

  let message = 'Error in deleting programming language';

  if (result.affectedRows) {
    message = 'Programming language deleted successfully';
  }

  return {message};
}

Don’t forget to export this function as well. Once again, to link up the service with the route, we’ll add the following code to the routes/programmingLanguages.js file:

/* DELETE programming language */
router.delete('/:id', async function(req, res, next) {
  try {
    res.json(await programmingLanguages.remove(req.params.id));
  } catch (err) {
    console.error(`Error while deleting programming language`, err.message);
    next(err);
  }
});

Testing our APIs

After you have the Node.js Express server running with node index.js, you can test all the API endpoints. To create a new programming language, let’s go with Dart, run the following cURLcommand. Alternately, you can use Postman or any other HTTP client:

curl -i -X POST -H 'Accept: application/json' \
    -H 'Content-type: application/json' http://localhost:3000/programming-languages \
    --data '{"name":"dart", "released_year": 2011, "githut_rank": 13, "pypl_rank": 20, "tiobe_rank": 25}'

The code above will result in the following output:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 55
ETag: W/"37-3mETlnRrtfrms6wlAjdgAXKq9GE"
Date: Mon, 01 Feb 2021 11:20:07 GMT
Connection: keep-alive

{"message":"Programming language created successfully"}

You can remove the X-Powered-By header and add other security response headers using Express.js Helmet, which will be a great addition to improve the API’s security. For now, let’s update the GitHut rank of Dart from 13 to 12:

curl -i -X PUT -H 'Accept: application/json' \
    -H 'Content-type: application/json' http://localhost:3000/programming-languages/17 \
    --data '{"name":"dart", "released_year": 2011, "githut_rank": 12, "pypl_rank": 20, "tiobe_rank": 25}'

The code above will generate an output like below:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 55
ETag: W/"37-0QPAQsRHsm23S9CNV3rPa+AFuXo"
Date: Mon, 01 Feb 2021 11:40:03 GMT
Connection: keep-alive

{"message":"Programming language updated successfully"}

To test out the DELETE API, you can use the following cURL to delete Dart with ID 17:

curl -i -X DELETE -H 'Accept: application/json' \
    -H 'Content-type: application/json' http://localhost:3000/programming-languages/17

The code above will result in the following output:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 55
ETag: W/"37-aMzd+8NpWQ09igvHbNLorsXxGFo"
Date: Mon, 01 Feb 2021 11:50:17 GMT
Connection: keep-alive

{"message":"Programming language deleted successfully"}

If you’re more used to a visual interface for testing, for instance, Postman, you can import the cURL commands into Postman.

Further considerations

For the sake of simplicity in this tutorial, we kept our example fairly simple. However, if this was a real-life API, and not a demo, I’d highly recommend the following:

  • Use a robust validation library like Joi to precisely validate the input, for example, to ensure the name of the programming language is required and doesn’t already exist in the database.

  • Improve security by adding Helmet.js to Express.js

  • Streamline logs in a more manageable way using a Node.js logging library like Winston

  • Use Docker for the Node.js application

Conclusion

We now have a functioning API server that uses Node.js and MySQL. In this tutorial, we learned how to set up MySQL on a free service. We then created an Express.js server that can handle various HTTP methods in connection to how it translates to SQL queries.

The example REST API in this tutorial serves as a good starting point and foundation for building real-world, production-ready REST APIs, wherein you can practice the additional considerations describes above. I hope you enjoyed this article, happy coding!

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.

Last updated