Building a Restful CRUD API with Node.js, Express, and Sequelize
Hi, in this article, we’ll be building a RESTful CRUD (Create, Retrieve, Update, Delete) API with Node.js, Express, and MySQL.
We’ll use Sequlize for interacting with the MySQL Database.
Prerequisites
We will build Rest API for creating, retrieving, updating & deleting users.
What is Sequelize?
Sequelize is a promise-based Node.js ORM(Object–relational mapping) for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication, and more.
Creating The Application And Install Dependencies
first thing first let’s create our project folder.
$ mkdir nodejs-sequelize
$ cd nodejs-sequelize
$ npm init
next, we will install the required modules.
$ npm install express mysql2 sequelize sequelize-cli
- express: One of the most popular web frameworks for Node.js.
- mysql2: Fast MySQL driver.
- sequelize: A powerful library in Javascript that makes it easy to manage a SQL database.
- sequelize-cli: Sequelize Command-Line Interface (CLI).
To create the project you will need to execute the init command
npx sequelize-cli init
This will create the following folders:
- config: contains config file, which tells CLI how to connect with database.
- models: contains all models for your project.
- migrations: contains all migration files.
- seeders: contains all seed files.
Connect To The Database
Create a database called usersdb so that we can connect to it.
Now, we need to tell the CLI how to connect to the database, to do that we need to edit the config.json file.
"development": {"username": "root","password": "password","database": "usersdb","host": "localhost","dialect": "mysql"}
Creating the Users Model
So, the first thing you need to understand is that whit Sequlize we create different tables as models, so instead of creating or table directly using SQL, let’s create a file called User.js in the models folder.
Now that we have a User model, let’s take a look at the app.js file.
The above code runs our server on port 3000 and we call the db.sequelize.sync() function to synchronize all the defined models to the database.
CRUD Operation
Creating a new User
the .create method used to insert a user into the database, based on the passed parameters.
Retrieving all Users
Retrieve all users from the database.
Retrieving a single User
Find a single user with a user id.
Updating a User
The .findByPk() method used to search for an entity whit the given primary key.
Deleting a User
We use .findByPk() to find a specific user by ID. Then, the .destroy() method removes the user from the database.
Testing our APIs
Creating a new User using POST /users API
Retrieve all Users using GET /users API
Retrieve a single User by id using GET /users/:id API
Update a User using PUT /users/:id API
Delete a User using DELETE /users/:id API