Posted on Updated on - Arjun

Creating a RESTful API with Express js, Node js/MySQl

Do you want to create a RESTful API with NodeJS/Express Js framework? Here is the tutorial, by reading this tutorial you can create our own REST api application server. Nowadays, it’s quite common to create web and mobile apps that consume data from apis. This is providing easy decoupling, client or server can be developed by different teams or same.

we are going to use a very popular web framework called Express to create REST apis.

What is Express js?

Express is a minimalist web framework that was highly inspired by the Sinatra framework from the Ruby language. With this module, you can create anything from small applications to large, complex ones. This framework allows you to build APIs and also to create simple web sites.

Here is main advantages of Express:
1. Easily integratable with template engines
2. No database or persistence data storage, you can integrate with any object relational mapping (ORM) or object data mappers (ODMs).
3. flexible and Robust routing.
4. Minimalist code
5. sophisticated middlewares concept.
6. A huge list of third-party middlewares to integrate

NOTE: You have to install NodeJs and MySQL softwares.

Database and table

Name your database whatever you want, and run below shown SQL it will create task table.

Insert some sample data into the tasks table.

Setup Node Restful Project

Go to Terminal or Command Line, create a project folder.

Initialize your node project with below npm command, which will create a file called package.json and it will ask few questions about project, if you want to avoid questions , use — yes flag.

Now install express js framework and MySQL driver with NPM.

Here is my final package.json file.

We are going to implement following API calls –

Method URL Action
GET /todos Retrieve all todos
GET /todos/search/bug Search for todos with ‘bug’ in their name
GET /todo/1 Retrieve todo with id == 1
POST /todo Add a new todo
PUT /todo Update todo with id == 1
DELETE /todo Delete todo with id == 1

Create Express Server

Create server.js file, Open it with editor, copy following code. Please read the comments for better understanding.

Express server is ready, you can start your server with node server.js command, to see output point your browser to http://localhost:8080.

Node MySQL – Database Connection

Update your server.js file with MySQL connection code. Here you have to modify the MySQL database name, host, username and password.

Implementing the API calls with express js

Now that we have our express serer up and running with database connection, we need to manage todos in the database.

Getting the Todos list – We are going to create a new route so that when a user hits /todos, it will return a list of all todos in JSON format. Update your server.js with below code.

This function simply return all todos information as you can see in this query, to call this API use this URL http://localhost:8080/todos.

Getting single todo – We are going to create a new route so that when a user hits /todo/{id}, it will return a todo in JSON format.

This function check record of given id and return if found anything, to call this API use this URL http://localhost:8080/todo/1.

Find todo by name – We are going to create a new route so that when a user hits /todos/search/{Query}, it will return a list of all matched todos in JSON format.

This function search in database for your given query, to call this API use this URL http://localhost:8080/todos/search/bug

Add todo – We are going to create a new route so that when a user sends a post request to /todo with required data, app will add a new record to the database.

This API accept post request and insert submitted data in your database. To call this API use this URL http://localhost:8080/todo

Delete Task – We are going to create a new route so that when a user sends a delete request to /todo/{id}, app will delete a record from the database.

Update Task – We are going to create a new route so that when a user sends a put request to /todo/{id} with required data, app will updated a record based on match parameter in the database.

This API accept put request and updates submitted data in your database. To call this API use this URL http://localhost:8080/todo/{id}

Here is the complete server.js file.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
  • There is an error in delete method. I think, that it should look like this

    app.delete(‘/todo/:id’, function (req, res) {

    let task_id = req.params.id;

    if (!task_id) {
    return res.status(400).send({ error: true, message: ‘Please provide text_id’ });
    }
    connection.query(‘DELETE FROM tasks WHERE id = ?’, task_id, function (error, results, fields) {
    if (error) throw error;
    return res.send({ error: false, data: results, message: ‘text has been updated successfully.’ });
    });
    })

    • What exactly the issue, Here? I am able to see only one difference here, you are passing id via URL instead of body.

      • you’re right, but I try your version of code and don’t want work – maybe error was on my use of this code.

  • Shantanu Saxena

    Great article for quick REST API development using mysql and express. Simple and step by step. Thanks Arjun for sharing!

    • Thanks for the words!.

DMCA.com Protection Status