{"id":18310998,"url":"https://github.com/cploutarchou/node_rest_api_with_mysql","last_synced_at":"2025-10-12T10:14:34.315Z","repository":{"id":42282851,"uuid":"252678922","full_name":"cploutarchou/node_rest_api_with_mysql","owner":"cploutarchou","description":"Node.js Rest APIs tutorial with Express, Sequelize \u0026 MySQL - phpMyAdmin","archived":false,"fork":false,"pushed_at":"2023-03-04T10:07:16.000Z","size":488,"stargazers_count":35,"open_issues_count":11,"forks_count":7,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-07-02T11:54:46.990Z","etag":null,"topics":["docker","docker-compose","express","express-js","node","node-js","nodejs","rest","rest-api","rest-client","sequilize","tutorial","tutorial-code"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cploutarchou.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-04-03T08:46:51.000Z","updated_at":"2025-06-05T02:55:10.000Z","dependencies_parsed_at":"2025-04-05T18:46:47.635Z","dependency_job_id":null,"html_url":"https://github.com/cploutarchou/node_rest_api_with_mysql","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/cploutarchou/node_rest_api_with_mysql","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cploutarchou%2Fnode_rest_api_with_mysql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cploutarchou%2Fnode_rest_api_with_mysql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cploutarchou%2Fnode_rest_api_with_mysql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cploutarchou%2Fnode_rest_api_with_mysql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cploutarchou","download_url":"https://codeload.github.com/cploutarchou/node_rest_api_with_mysql/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cploutarchou%2Fnode_rest_api_with_mysql/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274129094,"owners_count":25227170,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-08T02:00:09.813Z","response_time":121,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["docker","docker-compose","express","express-js","node","node-js","nodejs","rest","rest-api","rest-client","sequilize","tutorial","tutorial-code"],"created_at":"2024-11-05T16:16:07.120Z","updated_at":"2025-10-12T10:14:29.276Z","avatar_url":"https://github.com/cploutarchou.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"## How To Build Simple Node.js Rest APIs with Express, Sequelize \u0026 MySQL\n\nWe’ll be start to build a Node.js Rest API with Express, Sequelize \u0026 MySQL. Here we’ll use Sequelize for interacting with the **MySQL** instance.\n\n### **Required applications**\n\n*   **[Docker](https://www.docker.com/products/docker-desktop)** is a set of platform as a service product that uses OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels.\n*   **[Node.js](https://nodejs.org/en/)** is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications. Node.js is an open-source, cross-platform runtime environment for developing server-side and networking applications.\n*   **[ExpressJS](https://expressjs.com/)** is one of the most popular web frameworks for node.js. It is built on top of node.js HTTP module and adds support for routing, middleware, view system, etc. It is very simple and minimal, unlike other frameworks that try to do way too much, thereby reducing the flexibility for developers to have their own design choices.\n*   **[Sequelize](https://sequelize.org/)** is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.\n*   **[CORS](https://www.npmjs.com/package/cors)** is a _node_.js package for providing a Connect/Express middleware that can be used to enable _CORS_ with various options\n*   **[body-parser](https://github.com/expressjs/body-parser)** Parse incoming request bodies in a middleware before your handlers, available under the `req.body` property.\n*   [**Postman**](https://www.getpostman.com/) is an API(application programming interface) development tool that helps to build, test and modify APIs.It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH, etc.).\n\n### **Node.js Rest CRUD API overview**\n\nWe will build Rest Apis that can create, retrieve, update, delete and find Posts by title.\n\nFirst, we start with an Express web server. Next, we add configuration for MySQL database, create `Post` a model with Sequelize, write the controller. Then we define routes for handling all CRUD operations (including custom finder).\n\nThe following table shows overview of the Rest APIs that will be exported\n| Methods | Urls | Actions |\n|--|--|--|\n| GET | api/posts/all | Get all Posts |\n| GET | api/posts/:id| Get post by `id` |\n| POST |api/posts/create| Create new post |\n| PUT |api/posts/update/:id| Update post by `id` |\n| DELETE |api/posts/delete/:id| Delete post by `id` |\n| DELETE |api/posts/deleteall| Delete all posts| .\n| GET |api/posts/published| Get all published posts| \n| GET |api/posts?title=’test’| Get all posts which title contains `'test'`| \n| GET |api/posts/publisher?name=’christos’| Get All posts where publisher name is  `'christos'`| \n\nThis is our project structure:\n\n![enter image description here](https://christosploutarchou.com/wp-content/uploads/2020/04/folders_structure.png)\n\n### **Now let’s start Creating Node.js App**\n\nFirst, we create a folder:\n\n$ mkdir node\\_rest\\_api\\_with\\_mysql\n$ cd node\\_rest\\_api\\_with\\_mysql\n\nNext, we initialise the Node.js App with a package.json file:\n```json\nnpm init\n\nname: (nodejs-express-sequelize-mysql) \nversion: (1.0.0) \ndescription: Node.js Rest Apis with Express, Sequelize \u0026 MySQL.\nentry point: (index.js) server.js\ntest command: \ngit repository: \nkeywords: nodejs, express, sequelize, mysql, rest, api, docker\nauthor: Christos Ploutarchou\nlicense: (ISC)\n\nIs this ok? (yes) yes\n```\n**If your already have MySQL installed on you PC you can ignore following Steps**\n\n### **Next, need to install docker for mysql and phpMyAdmin.**\n\n1.  Install Docker (Learn more about docker installation [here](https://docs.docker.com/install/))\n2.  Enter on the project root directory \n3.  Up the compose\n\ndocker-compose up -d\n\n*   Access phpmyadmin\n\nyour\\_ip:8183\nServer: mysql\nUsername: root/root\nPassword: root/pass\n\n*   Access mysql on terminal\n\n docker exec -it mysql\\_container\\_name mysql -u root -p\n\n### **Docker phpmyadmin ENV**\n\nPMA\\_ARBITRARY \n\nwhen set to 1 connection to the arbitrary server will be allowed\n\nPPMA\\_HOST \n\ndefine address/host name of the MySQL server\n\nPMA\\_PORT \n\ndefine port of the MySQL server\n\n*   If you need more information about phpmyadmin image. [READ HERE](https://hub.docker.com/r/phpmyadmin/phpmyadmin/)\n*   If you need more information about mysql image. [READ HERE](https://hub.docker.com/_/mysql/)\n\nWe need also to install necessary modules: `express`, `sequelize`, `mysql2` and `body-parser` on our project.\n\nRun the command:\n\nnpm install express body-parser cors  sequelize mysql2 --save\n\nWhen installation finish package.json file should look like this:\n```package.json\n{\n  \"name\": \"node_rest_api_with_mysql\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Node.js Rest Api with Express, Sequelize, MySQL \u0026 phpMyAdmin .\",\n  \"main\": \"server.js\",\n  \"scripts\": {\n    \"start\": \"nodemon server.js\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/cploutarchou/node_rest_api_with_mysql.git\"\n  },\n  \"keywords\": [\n    \"node\",\n    \"rest-api\",\n    \"tutorial\",\n    \"mysql\",\n    \"phpMyAdmin\",\n    \"docker\",\n    \"node.js\",\n    \"sequilize\"\n  ],\n  \"author\": \"Christos Ploutarchou\",\n  \"license\": \"ISC\",\n  \"bugs\": {\n    \"url\": \"https://github.com/cploutarchou/node_rest_api_with_mysql/issues\"\n  },\n  \"homepage\": \"https://github.com/cploutarchou/node_rest_api_with_mysql#readme\",\n  \"dependencies\": {\n    \"body-parser\": \"^1.19.0\",\n    \"cors\": \"^2.8.5\",\n    \"express\": \"^4.17.1\",\n    \"mysql2\": \"^2.1.0\",\n    \"sequelize\": \"^5.21.5\"\n  },\n  \"devDependencies\": {\n    \"eslint\": \"^6.8.0\",\n    \"eslint-config-standard\": \"^14.1.1\",\n    \"eslint-plugin-import\": \"^2.20.2\",\n    \"eslint-plugin-node\": \"^11.1.0\",\n    \"eslint-plugin-promise\": \"^4.2.1\",\n    \"eslint-plugin-standard\": \"^4.0.1\",\n    \"nodemon\": \"^2.0.2\"\n  }\n}\n\n```\n### **Setup Express web server**\n\nIn our root directory need to create a new _server.js_ file:\n```javascript\nconst express = require(\"express\");\nconst bodyParser = require(\"body-parser\");\nconst cors = require(\"cors\");\nconst server = express();\nconst db = require(\"./models\");\nconst corsSettings = {\n  originL: \"http://localhost:8081\"\n};\n\nconst api = require(\"./routes/index\");\nserver.use(cors(corsSettings));\n\n// Parse request of content-type - application/json\nserver.use(bodyParser.json());\n\n// parse requests of content-type -application/x-www-form-urlencoded\nserver.use(bodyParser.urlencoded({ extended: true }));\n\ncreate a simple route\nserver.get(\"/\", (\\_req, res) =\u003e {\n   res.json({ message: \"Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou\" });\n});\n\n// set listening ports for request\nconst port = process.env.PORT || 8080;\n\nserver.listen(port, () =\u003e {\n  console.log(\"Server running on port : \" + port );\n});\n```\nWhat we are doing here:  \n– import `express`, `body-parser` and `cors` modules:\n\n*   Express is for building the Rest apis.\n*   [body-parser](https://www.npmjs.com/package/body-parser) helps to parse the request and create the `req.body` object.\n*   [cors](https://www.npmjs.com/package/cors) provides Express middleware to enable CORS with various options.\n\n– create an Express app, then add `body-parser` and `cors` middlewares using `app.use()` method. Notice that we set origin: `http://localhost:8081`.  \n– define a GET route which is simple for test.  \n– listen on port 8080 for incoming requests.\n\nNow let’s run the app by running the following command : `node server.js`.  \nOpen your browser with URL [http://localhost:8080/](http://localhost:8080/), you will see:\n\n![enter image description here](https://christosploutarchou.com/wp-content/uploads/2020/04/localhost-1024x264.png)\n\nYes Correct, the first step is done. We’re gonna work with Sequelize in the next section.\n\n### **Configure MySQL database \u0026 Sequelize**\n\nIn the root folder, we create a separate _config_ folder for configuration with db.config.js file like this:\n\n**Note:** If you don’t user project docker compose, Then need to **update** database info with your local environment credentials and info.\n```javascript\nmodule.exports = {\n  HOST: \"localhost\",\n  USER: \"root\",\n  PASSWORD: \"pass\",\n  DB: \"restapi\",\n  dialect: \"mysql\",\n  pool: {\n    max: 10,\n    min: 0,\n    acquire: 30000,\n    idle: 50000\n  }\n};\n```\nThe first five parameters are for MySQL connection.  \n`pool` is optional, it will be used for Sequelize connection pool configuration:\n\n*   `max`: maximum number of connection in pool\n*   `min`: minimum number of connection in pool\n*   `idle`: maximum time, in milliseconds, that a connection can be idle before being released\n*   `acquire`: maximum time, in milliseconds, that pool will try to get connection before throwing error\n\nFor more information, you can visit [API Reference for the Sequelize constructor](https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor).\n\n### **Initialize Sequelize**\n\nWe’re gonna initialise Sequelize in **app**/**models** folder that will contain model in the next step.\n\nNow create **app/models**/index.js with the following code:\n```javascript\nconst dbConfig = require(\"../config/db.config\");\nconst Sequelize = require(\"sequelize\");\nconst database = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {\n  host: dbConfig.HOST,\n  dialect: dbConfig.dialect,\n  operatorsAliases: false,\n  pool: {\n    max: dbConfig.pool.max,\n    min: dbConfig.pool.min,\n    acquire: dbConfig.pool.acquire,\n    idle: dbConfig.pool.idle\n  }\n});\n\nconst db = {};\ndb.Sequelize = Sequelize;\ndb.databaseConf = database;\n// function to drop existing tables and re-sync database\ndb.dropRestApiTable = () =\u003e {\n  db.databaseConf.sync({ force: true }).then(() =\u003e {\n    console.log(\"restTutorial table just dropped and db re-synced.\");\n  });\n};\ndb.posts = require(\"./Sequelize.model\")(database, Sequelize);\nmodule.exports = db;\n```\nDon’t forget to call `sync()` method in _server.js_:\n```javascript\nconst db = require(\"./models\");\ndb.databaseConf.sync();\n```\nAfter that your server.js file must look like below:\n```javascript\nconst express = require(\"express\");\nconst bodyParser = require(\"body-parser\");\nconst cors = require(\"cors\");\nconst server = express();\nconst db = require(\"./models\");\nconst corsSettings = {\n  originL: \"http://localhost:8081\"\n};\nserver.use(cors(corsSettings));\n\nconst db = require(\"./models\");\n\n// Parse request of content-type - application/json\nserver.use(bodyParser.json());\n\n// parse requests of content-type -application/x-www-form-urlencoded\nserver.use(bodyParser.urlencoded({ extended: true }));\n\ncreate a simple route\nserver.get(\"/\", (\\_req, res) =\u003e {\n   res.json({ message: \"Welcome to node.js rest api application. Created for learning purposes by Christos Ploutarchou\" });\n});\n\n// set listening ports for request\nconst port = process.env.PORT || 8080;\n\nserver.listen(port, () =\u003e {\n  console.log(\"Server running on port : \" + port );\n});\ndb.databaseConf.sync();\n```\n### **Define the Sequelize Model**\n\nIn models folder, create **Sequelize.model.js** file like this:\n```javascript\nmodule.exports = (database, Sequelize) =\u003e {\n  return database.define(\"restTutorial\", {\n    title: {\n      type: Sequelize.STRING\n    },\n    description: {\n      type: Sequelize.TEXT\n    },\n    published: {\n      type: Sequelize.BOOLEAN\n    },\n    publisher: {\n      type: Sequelize.STRING\n    }\n  });\n};\n```\nThis Sequelize Model represents **posts** table in MySQL database. These columns will be generated automatically: _id_, _title_, _description_, _published_, publisher, _createdAt_, _updatedAt_.\n\nAfter initializing Sequelize, we don’t need to write CRUD functions, Sequelize supports all of them:\n\n*   Create a new post : `[create(object)](https://sequelize.org/master/class/lib/model.js~Model.html#static-method-create)`\n*   Get all posts: `[findAll](https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAll)()`\n*   Update a post by id: `[update(data, where: { id: id })](https://sequelize.org/master/class/lib/model.js~Model.html#static-method-update)`\n*   Delete a post : `[destroy](https://sequelize.org/master/class/lib/model.js~Model.html#static-method-destroy)(where: { id: id })`\n*   Delete all posts: `destroy(where: {})`\n*   Get all post by title: `findAll({ where: { title: ... } })`\n*   Get all post by publisher name: `findAll({ where: { publisher: ... } })`\n\nThese functions will be use it on our Controller.\n\n### **Create the Controller**\n\nInside **app**/**controllers** folder, let’s create Post.js with these CRUD functions:\n\n*   create\n*   findAll\n*   findOne\n*   update\n*   delete\n*   deleteAll\n*   findAllPublished\n*   findByPublisherName\n```javascript\nconst db = require('../models')\nconst postObj = db.posts\nconst Op = db.Sequelize.Op\n\n// Create and save new Post\nexports.create = (request, result) =\u003e {\n}\n\n// Save Post object to db\npostObj.create(post).then(data =\u003e {\n\n}\n\n// Retrieve all Post (Receive data with condition).\nexports.getAllPosts = (request, result) =\u003e {\n\n}\n\n// Get Post object by ID\nexports.getPostByID = (request, result) =\u003e {\n\n}\n// Update a Post object by the id\nexports.updatePostByID = (request, result) =\u003e {\n\n}\n\n// Delete Post object by ID\nexports.deletePostByID = (request, result) =\u003e {\n\n}\n\n// Delete All Posts objects from database\nexports.deleteAllPosts = (request, result) =\u003e {\n\n}\n\n// Get all published Post\nexports.getAllPublishedPosts = (request, result) =\u003e {\n\n}\n\n// Get all published Post by Publisher Name\nexports.getAllPostsByPublisherName = (request, result) =\u003e {\n\n}\n\n// Get all published post by Title\nexports.getPostByTitle = (request, result) =\u003e {\n\n}\n```\nNow Let’s implement these functions.\n\n### Create a new post object\n```javascript\n// Create and save new Post\nexports.create = (request, result) =\u003e {\n  if (!request.body.title) {\n    result.status(400).send({\n      message: \"Content cannot be empty\"\n    });\n  }\n\n  // Create a Post object\n  const post = {\n    title: request.body.title,\n    description: request.body.description,\n    published: request.body.published ? request.body.published : false,\n    publisher: request.body.publisher ? request.body.publisher : false\n  };\n\n  // Save Post object to db\n  postObj.create(post).then(data =\u003e {\n    result.send(data);\n  }).catch(err =\u003e {\n    result.status(500).send({\n      message: err.message || \"Some error occurred while saving.\"\n    });\n  });\n};\n```\n### **Get all objects (By post title)**\n```javascript\n// Get all published post by Title\nexports.getPostByTitle = (request, result) =\u003e {\n  const title = request.query.title;\n  postObj.findAll({\n    where: {\n      publisher: { \\[Op.like\\]: `%${title}%` },\n      published: true\n    }\n  }).then(data =\u003e {\n    result.send(data);\n  }).catch(err =\u003e {\n    result.status(500).send({\n      message: err.message || \"Something going wrong. Unable to retrieve data!\"\n    });\n  });\n};\n```\nOn that function we use `request.query.title` to get query string from the Request and consider it as condition for `findAll()` method.\n\n### **Get single post object (By post ID)**\n```javascript\n// Get Post object by ID\nexports.getPostByID = (request, result) =\u003e {\n  const paramID = request.params.id;\n  console.log(paramID);\n  console.log(paramID);\n  postObj.findAll({\n    where: { id: paramID }\n  }).then(data =\u003e {\n    result.send(data);\n  }).catch(err =\u003e {\n    result.status(500).send({\n      message: err.message || `Some error occurred while retrieving data with id : ${paramID}`\n    });\n  });\n};\n```\n### Update a Post object by the id\n```javascript\n// Update a Post object by the id\nexports.updatePostByID = (request, result) =\u003e {\n  const id = request.params.id;\n  postObj.update(request.body, {\n    where: { id: id }\n  }).then(num =\u003e {\n    if (num === 1) {\n      result.send({\n        message: \"Post object successfully updated.\"\n      });\n    } else {\n      result.send({\n        message: `Cannot update Post object with id=${id}!`\n      });\n    }\n  }).catch(err =\u003e {\n    result.status(500).send({\n      message: err.message || `Error while updating Post object with id=${id}!`\n    });\n  });\n};\n```\n### **Delete Post object by ID**\n```javascript\n// Delete Post object by ID\nexports.deletePostByID = (request, result) =\u003e {\n  const id = request.params.id;\n  postObj.destroy({\n    where: { id: id }\n  }).then(num =\u003e {\n    if (num === 1) {\n      result.send({\n        message: \"Post object successfully deleted.\"\n      });\n    } else {\n      result.send({\n        message: `Cannot delete Post object with id=${id}!`\n      });\n    }\n  }).catch(err =\u003e {\n    result.status(500).send({\n      message: err.message || `Cannot delete Post object with id=${id}!`\n    });\n  });\n};\n```\n### Delete All Posts objects from database\n```javascript\n// Delete All Posts objects from database\nexports.deleteAllPosts = (request, result) =\u003e {\n  postObj.destroy({\n    where: {},\n    truncate: false\n  }).then(nums =\u003e {\n    result.send({\n      message: `${nums} Post objects was deleted successfully!`\n    });\n  }).catch(err =\u003e {\n    result.status(500).send({\n      message: err.message || \"Cannot delete Post objects. Something going wrong}!\"\n    });\n  });\n};\n```\n### Get all published Posts objects from database\n```javascript\n// Get all published Post\nexports.getAllPublishedPosts = (request, result) =\u003e {\n  postObj.findAll({\n    where: { published: true }\n  }).then(data =\u003e {\n    result.send(data);\n  }).catch(err =\u003e {\n    result.status(500).send({\n      message: err.message || \"Something going wrong. Unable to retrieve data!\"\n    });\n  });\n};\n```\n### Get all published Posts objects from database\n```javascript\nexports.getAllPosts = (request, result) =\u003e {\n  postObj.findAll()\n    .then(data =\u003e {\n      result.send(data);\n    }).catch(err =\u003e {\n      result.status(500).send({\n        message: err.message || \"Some error occurred while retrieving data.\"\n      });\n    });\n};\n```\n### **Define Routes**\n\nWhen a client sends request for an endpoint using HTTP request (GET, POST, PUT, DELETE), we need to determine how the server will reponse by setting up the routes.\n\nLet’s now create a a **index.js** file inside routes/ folder with content like this:\n```javascript\nconst post = require(\"../controllers/Post\");\nconst express = require(\"express\");\nconst router = express.Router();\n// Create New Post\nrouter.post(\"/api/posts/create\", post.create);\n// // Retrieve all posts\nrouter.get(\"/api/posts/all\", post.getAllPosts);\n// Retrieve all Published posts\nrouter.get(\"/api/posts/published\", post.getAllPublishedPosts);\n// Retrieve all Published posts by Publisher Name\nrouter.get(\"/api/posts/publisher\", post.getAllPostsByPublisherName);\n// Retrieve all posts by title\nrouter.get(\"/api/posts\", post.getPostByTitle);\n// Retrieve post by ID\nrouter.get(\"/api/posts/:id\", post.getPostByID);\n// // Update post by ID\nrouter.put(\"/api/post/update/:id\", post.updatePostByID);\n// // Delete post by ID\nrouter.delete(\"/api/post/delete/:id\", post.deletePostByID);\n// Delete all posts\nrouter.delete(\"/api/posts/deleteAll\", post.deleteAllPosts);\n\nmodule.exports = router;\n```\nYou can see that we use a controller from `..controllers/Post`.\n\nWe also need to include routes in _server.js_ (right before `app.listen()`):\n```javascript\nconst api = require(\"./routes/index\");\n\nserver.use(\"/\", api);\n```\nAfter that update our server.js file must look like:\n```javascript\nconst express = require(\"express\");\nconst bodyParser = require(\"body-parser\");\nconst cors = require(\"cors\");\nconst server = express();\nconst db = require(\"./models\");\nconst corsSettings = {\n  originL: \"http://localhost:8081\"\n};\n\nconst api = require(\"./routes/index\");\nserver.use(cors(corsSettings));\n// Parse request of content-type - application/json\nserver.use(bodyParser.json());\n// parse requests of content-type -application/x-www-form-urlencoded\nserver.use(bodyParser.urlencoded({ extended: true }));\n\nserver.use(\"/\", api);\n\n// set listening ports for request\nconst port = process.env.PORT || 80;\n\nserver.listen(port, () =\u003e {\n  console.log(`Server running on port : ${port}`);\n});\n```\n**Note** : In development, you may need to drop existing tables and re-sync database. So let’s create a new function on models/index.js to apply that.\n\nAdd following function on index.js\n```javascript\ndb.dropRestApiTable = () =\u003e {\n  db.databaseConf.sync({ force: true }).then(() =\u003e {\n    console.log(\"restTutorial table just dropped and db re-synced.\");\n  });\n};\n```\nYou can call that function on server.js file when you want drop existing table:\n```javascript\ndb.dropRestApiTable();\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcploutarchou%2Fnode_rest_api_with_mysql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcploutarchou%2Fnode_rest_api_with_mysql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcploutarchou%2Fnode_rest_api_with_mysql/lists"}