How to Create RESTful APIs on Node.js with TypeORM CLI

How to Create RESTful APIs on Node.js with TypeORM CLI

Get Started with TypeORM, MySQL, and Express.js. Use TypeORM CLI to easily create RESTful APIs on Node.js

TypeORM connects applications to databases. In this article, I’ll show you how to quickly create a new RESTful API microservice on Express (NodeJS) that integrates with MySQL using TypeORM.

ORM is the bridge between the API and your database

If you’re already familiar with using ORMs, let’s jump to one liners.

Outline

  1. Definitions
  2. Prerequisites
  3. One Liners
  4. Testing
Definitions
  • TypeORM — According to their website, “TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8).”
  • Object-reltaional mapping (ORM) — connects apps to databases. You can think of it as using code at the app level to execute queries.
  • MySQL — a popular open-source relational database.
  • Express — web framework for NodeJS.
  • RESTful API — WTF is an API?
Prerequisites
  • NPM
  • MySQL
  • Docker (if you don’t have MySQL)
One Liners

1. Install TypeORM

npm install typeorm

2. Initialize

typeorm init --name user-microservice --database mysql --express

Explanation: This command creates a new TypeORM project with the name user-microservice and scaffolds the necessary code to use Express and MySQL.

Easy! We just created a Node.js project which includes routes, controller, and entity

Explanation: routes.ts is the entry point for the API. UserController.tsis the orchestrator between routes and entity. User.tsis the entity that defines the table schema for the database.

Pause for a minute to look at the code inside each file and see how each of the pieces connect with each other. Notice any patterns?

3. Install packages

cd user-microservice
npm install

4. Database configurations

If you have MySQL already, run a local instance of it, and update the connection settings in ormconfig.json.

Otherwise, use the following Docker command:

docker run --name songtham-mysql -e MYSQL_ROOT_PASSWORD=test -e MYSQL_USER=test -e MYSQL_PASSWORD=test -e MYSQL_DATABASE=test -p 3306:3306 -d mysql:latest --default-authentication-plugin=mysql_native_password

Explanation: This Docker command grabs the latest MySQL version and runs it locally on your computer. Note: If you run this, you don’t need to make any changes to ormconfig.json, as it’s mapped to the default config file already.

5. Start

npm start
Testing

If you did everything correctly, you should see the following message:

Express server has started on port 3000. Open http://localhost:3000/users to see results

GET

Navigate to http://localhost:3000/users, and you’ll see on the page:

[{"id":1,"firstName":"Timber","lastName":"Saw","age":27},{"id":2,"firstName":"Phantom","lastName":"Assassin","age":24}]

You might be wondering, “How did these users appear in the database?”

If you take a look inside index.ts,you can see starting the server creates the users with the following lines of code:

// insert new users for test

await connection.manager.save(connection.manager.create(User, {

firstName: “Timber”,

lastName: “Saw”,

age: 27

}));

await connection.manager.save(connection.manager.create(User, {

firstName: “Phantom”,

lastName: “Assassin”,

age: 24

}));

POST

To add a new record to the users table, run the following CURL command:

curl -d ‘{“firstName”:”Bob”, “lastName”:”Ross”, “age”:”52"}’ -H “Content-Type: application/json” -X POST http://localhost:3000/users

If done correctly, you should get a new entry in your database, and you’ll see the same entry if you go to http://localhost:3000/users.

[{"id":1,"firstName":"Timber","lastName":"Saw","age":27},{"id":2,"firstName":"Phantom","lastName":"Assassin","age":24},{"id":3,"firstName":"Bob","lastName":"Ross","age":52}]
Closing

TypeORM is an easy-to-use ORM that with one line can scaffold new apps that connect to databases. You can use it to quickly create new projects and/or microservices.

This guide covers the basics of using the CLI to initialize a new app, to connect it to MySQL, and to perform GET and POST API requests.

Thank you for reading!

Resources

Node.js API Tutorial for Beginners - Building API using NodeJS

Node.js API Tutorial for Beginners - Building API using NodeJS

Learn Node.js - Node.js API Development for Beginners, you'll learn the core fundamentals of NodeJS so that you can start building API using NodeJS. You will learn Modern JavaScript, NodeJS event loop, Asynchronous programming, using node modules, npm modules and creating your own modules, creating server, connect to database and sending json responses.

Learn Node.js - Node.js API Development for Beginners, you'll learn the core fundamentals of NodeJS so that you can start building API using NodeJS. You will learn Modern JavaScript, NodeJS event loop, Asynchronous programming, using node modules, npm modules and creating your own modules, creating server, connect to database and sending json responses.

APIs for Beginners - What is an API? How to use an API?

APIs for Beginners - What is an API? How to use an API?

APIs for Beginners, What exactly is an API? How do you use an API? Learn all about APIs in this full course for beginners. Learn how to use Postman and helper libraries in both JavaScript and Python. Lean how to create a project using an API using both Node.js and Flask. Learn what APIs do, why APIs exist, and the many benefits of APIs. Explore APIs online

APIs for Beginners - What is an API? How do you use an API? Learn all about APIs (Application Programming Interfaces) in this full course for beginners. You will learn what APIs do, why APIs exist, and the many benefits of APIs. APIs are used all the time in programming and web development so it is important to understand how to use them.

You will also get hands-on experience with a few popular web APIs. As long as you know the absolute basics of coding and the web, you'll have no problem following along.

⭐️ Course Contents ⭐️

⭐️ Unit 1 - What is an API
⌨️ Video 1 - Welcome (0:00:00)
⌨️ Video 2 - Defining Interface (0:03:57)
⌨️ Video 3 - Defining API (0:07:51)
⌨️ Video 4 - Remote APIs (0:12:55)
⌨️ Video 5 - How the web works (0:17:04)
⌨️ Video 6 - RESTful API Constraint Scavenger Hunt (0:22:00)

⭐️ Unit 2 - Exploring APIs
⌨️ Video 1 - Exploring an API online (0:27:36)
⌨️ Video 2 - Using an API from the command line (0:44:30)
⌨️ Video 3 - Using Postman to explore APIs (0:53:56)
⌨️ Video 4 - Please please Mr. Postman (1:03:33)
⌨️ Video 5 - Using Helper Libraries (JavaScript) (1:14:41)
⌨️ Video 6 - Using Helper Libraries (Python) (1:24:40)

⭐️ Unit 3 - Using APIs
⌨️ Video 1 - Introducing the project (1:34:18)
⌨️ Video 2 - Flask app (1:36:07)
⌨️ Video 3 - Dealing with API Limits (1:50:00)
⌨️ Video 4 - JavaScript Single Page Application (1:54:27)
⌨️ Video 5 - Moar JavaScript and Recap (2:07:53)
⌨️ Video 6 - Review (2:18:03)

How to Build a simple MySQL data access API using ExpressJS and NodeJS

How to Build a simple MySQL data access API using ExpressJS and NodeJS

In this article, we are looking into the introduction of Node.JS and Express.JS and then, I am going to build a simple MySQL data access API using Express.js, NodeJS.

In this article, we are looking into the introduction of Node.JS and Express.JS and then, I am going to build a simple MySQL data access API using Express.js, NodeJS.

I am going to demonstrate how we can create MySQL data access API using Node.JS and Express.js.

Let’s start with creating a folder as “sample-api”.

  • Open a folder in command prompt and type ‘npm init’ to initiate the project.
  • Enter details like project name, version, description etc. then type ’Yes’.
  • It will create a JSON file inside sample-api folder which contains the information regarding the project and NPM package that are needed into this project. We called dependencies.
  • Now, we are creating a MySQL table for users and their transaction details, as below.
--  
-- Table structure for table `users`  
--  
DROP TABLE IF EXISTS `users`;  
CREATE TABLE `users` (  
  `UserID` int(11) NOT NULL AUTO_INCREMENT,  
  `Name` varchar(45) DEFAULT NULL,  
  PRIMARY KEY (`UserID`)  
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;  
  
--  
-- Table structure for table `transactions`  
--  
DROP TABLE IF EXISTS `transactions`;  
CREATE TABLE `transactions` (  
  `TransactionId` int(11) NOT NULL AUTO_INCREMENT,  
  `UserId` int(11) DEFAULT NULL,  
  `TransactionAmount` decimal(10,2) DEFAULT NULL,  
  `Balance` decimal(10,2) DEFAULT NULL,  
  `TransactionDate` date DEFAULT NULL,  
  PRIMARY KEY (`TransactionId`)  
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;  
  • Then, we are installing NPM packages for MySQL to make MySQL connection and fetch insert, update records, express to build HTTP server, maintaining server route, body-parser to parsing body into JSON format by entering this command.
  • We can see that the packages are added to the node_modules folder in our project folder (sample-api). And, I have created this type of folder structure for our project. There are no specific rules regarding project structure, but we are maintaining everything with the modular design to keep it separate and well-maintained.
  • Now, we are creating MySQLConnect module for establishing the connection with MySQL and executing the MySQL queries.
  • For that, we have created ‘connection/MySQLConnect.JS’ file.
// establish Mysql Connection  
var mysql = require('mysql');  
  
function MySQLConnect() {  
  
  this.pool = null;  
    
  // Init MySql Connection Pool  
  this.init = function() {  
    this.pool = mysql.createPool({  
      connectionLimit: 10,  
      host     : 'localhost',  
      user     : 'root',  
      password : '[email protected]',  
      database: 'sample-db'  
    });  
  };  
  
  // acquire connection and execute query on callbacks  
  this.acquire = function(callback) {  
  
    this.pool.getConnection(function(err, connection) {  
      callback(err, connection);  
    });  
  
  };  
  
}  
  
module.exports = new MySQLConnect();  
  • Then, I have created ‘data_access/transaction.js’ file for acquiring the MySQL connection and return the response with data.
//methods for fetching mysql data  
var connection = require('../connection/MySQLConnect');  
  
function Transaction() {  
  
    // get all users data   
    this.getAllUsers = function (res) {  
        // initialize database connection  
        connection.init();  
        // calling acquire methods and passing callback method that will be execute query  
        // return response to server   
        connection.acquire(function (err, con) {  
            con.query('SELECT DISTINCT * FROM users', function (err, result) {  
                con.release();  
                res.send(result);  
            });  
        });  
    };  
  
    this.getTransactionById = function (id, res) {  
        // initialize database connection  
        connection.init();  
        // get id as parameter to passing into query and return filter data  
        connection.acquire(function (err, con) {  
            var query = 'SELECT date_format(t.TransactionDate,\'%d-%b-%Y\') as date, ' +  
                'CASE WHEN t.TransactionAmount >= 0 THEN t.TransactionAmount ' +  
                'ELSE 0 END AS Credit, CASE WHEN t.TransactionAmount < 0 THEN ' +  
                't.TransactionAmount ELSE 0 END AS Debit, t.Balance FROM ' +  
                'transactions t INNER JOIN users u ON t.UserId=u.UserID WHERE t.UserId = ?;';  
            con.query(query, id, function (err, result) {  
                    con.release();  
                    res.send(result);  
                });  
        });  
    };  
  
}  
  
module.exports = new Transaction();  
  • Now, I have developed routes for returning the data based on each request. So, I have added ‘route/route.js’ file.
//custom route for fetching data  
var transactions = require('../data_access/transaction');  
  
module.exports = {  
    //set up route configuration that will be handle by express server  
    configure: function (app) {  
  
        // adding route for users, here app is express instance which provide use  
        // get method for handling get request from http server.   
        app.get('/api/users', function (req, res) {  
            transactions.getAllUsers(res);  
        });  
  
        // here we gets id from request and passing to it transaction method.  
        app.get('/api/transactions/:id/', function (req, res) {  
            transactions.getTransactionById(req.params.id, res);  
        });  
  
    }  
};  
  • Now, we are writing the code for setting up the server using Express and here, we initialize the database connection and set route configuration with application.
/**  
 * Creating server using express.js 
 * http://localhost:8000/api/users 
 * http://localhost:8000/api/transactions/1 
*/  
var express = require('express');  
var bodyparser = require('body-parser');  
  
var routes = require('./routes/route');  
  
// creating server instance  
var app = express();  
  
// for posting nested object if we have set extended true  
app.use(bodyparser.urlencoded({ extended : true}));  
  
// parsing JSON  
app.use(bodyparser.json());  
  
//set application route with server instance  
routes.configure(app);  
  
// listening application on port 8000  
var server = app.listen(8000, function(){  
    console.log('Server Listening on port ' + server.address().port);  
});  
  • Our API is created; we can verify the API by running the server on localhost. To run our Server, we enter ‘npm start’ command in console. The npm start command is run on the node with starting page which we have set ‘main’ (server.js) key in package.json file. The server is ready for listening on port 8000.

We are verifying our API call by requesting it from the below URL.

  • http://localhost:8000/api/users

  • http://localhost:8000/api/transactions/1

Conclusion

In this article, we have looked into introduction of Node.JS and Express.JS, and we have created simple MySQL data access API using Express.js.

You can find the entire code on GitHub.

Thank you for reading!