{
    "componentChunkName": "component---src-templates-blog-post-js",
    "path": "/node-express-typescript-sequelize-mysql-rest-api/",
    "result": {"data":{"site":{"siteMetadata":{"title":"CrewCode Solutions"}},"markdownRemark":{"id":"03f05a1d-ad5f-5c4b-a5d2-d6a02f510ad8","excerpt":"In this article i will explain you step by step to setup REST Api with node, express , sequelize, mysql and typescript Step 1: Install typescript globally We…","html":"<p>In this article i will explain you step by step to setup REST Api with node, express , sequelize, mysql and typescript</p>\n<h4>Step 1: Install typescript globally</h4>\n<p>We need to install typescript globally in our computer so that <strong><em>we can use typescript command easily</em></strong> you can use npm or yarn i will use npm here, use the command below to install typescript</p>\n<pre><code class=\"language-js\">npm install -g typescript\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-sequelize-typescript-1.png\" alt=\"typescript-install\"></p>\n<h4>Step 2: Initialize typescript compiler</h4>\n<p>We need to intialize typescript compiler in order to compile our code to typescript, <strong><em>go to project folder and use below command to initialize typescript compiler</em></strong> this will create tsconfig.json file at the root path of your project</p>\n<pre><code class=\"language-js\">tsc --init\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-sequelize-typescript-2.png\" alt=\"typescript-compiler\"></p>\n<h4>Step 3: Initialize npm</h4>\n<p>Initialize npm to create package.json file so that you can install necessary package required by the project or start the project or for other purposes where you need to run npm command, <strong><em>run below command to initialize npm</em></strong></p>\n<pre><code class=\"language-js\">npm init\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-sequelize-typescript-3.png\" alt=\"npm-init\"></p>\n<h4>Step 4: Change the required configuration in tsconfig.json file for your project and create a src folder in your project root path</h4>\n<p>Change the <strong><em>outDir</em></strong>, <strong><em>rootDir</em></strong> in your tsconfig.json file outDir is the path where typescript compiled file will be stored and rootDir is the path where you main project code exists, I'm defining the path folder path as <strong><em>outDir: './dist'</em></strong> and <strong><em>rootDir:'./src'</em></strong></p>\n<p>Also <strong><em>create a folder name src at root path of project</em></strong> where we will be storing our project files</p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-sequelize-typescript-4.png\" alt=\"tsconfig-file\"></p>\n<h4>Step 5: Install required package express.js and body parser,nodemon, node types using npm</h4>\n<p>We will use npm command to install express.js and body parser, use below command to <strong><em>install the package express.js and body-parser and mongoose which helps in connecting to mongodb database</em></strong></p>\n<pre><code class=\"language-js\">npm install --save express body-parser sequelize sequelize-typescript mysql2\n</code></pre>\n<p>Use below command to install nodemon as development dependency</p>\n<pre><code class=\"language-js\">npm install --save-dev nodemon\n</code></pre>\n<p>Use below command to install node types so that typescript understands the node js code and doesn't throw error</p>\n<pre><code class=\"language-js\">npm install --save-dev @types/node\nnpm install --save-dev @types/express\n</code></pre>\n<h4>Step 6: Creating Node, express server and starting the server</h4>\n<p><strong><em>Create app.ts file under src folder in your project</em></strong> which we have created previously and copy paste code below in your app.ts file</p>\n<pre><code class=\"language-js\">import express from \"express\";\n\nconst app = express();\n\napp.listen(3000);\n</code></pre>\n<p><strong><em>Update your package.json file</em></strong> and add start command under script tag to compile typescript code and start the express server</p>\n<pre><code class=\"language-js\">\"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" &#x26;&#x26; exit 1\",\n    \"start\": \"tsc &#x26;&#x26; nodemon dist/app.js\"\n  },\n</code></pre>\n<p>After updating package.json file you can use below command to start the express server</p>\n<pre><code class=\"language-js\">npm start\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-sequelize-typescript-5.png\" alt=\"npm-start\"></p>\n<h4>Step 7: Creating routes, controller , model folder, connecting to mysql using sequelize and testing REST api</h4>\n<p><strong><em>Create a folder name controller inside src folder and create a file name todos.ts</em></strong> which is controller file and copy paste below code</p>\n<pre><code class=\"language-js\">import { RequestHandler } from \"express\";\n\nimport { Todos } from \"../models/todos\";\n\nexport const createToDo: RequestHandler = async (req, res, next) => {\n  var todos = await Todos.create({ ...req.body });\n  return res\n    .status(200)\n    .json({ message: \"Todo created successfully\", data: todos });\n};\n\nexport const deleteToDo: RequestHandler = async (req, res, next) => {\n  const { id } = req.params;\n  const deletedTodo: Todos | null = await Todos.findByPk(id);\n  await Todos.destroy({ where: { id } });\n  return res\n    .status(200)\n    .json({ message: \"Todo deleted successfully\", data: deletedTodo });\n};\n\nexport const getAllToDo: RequestHandler = async (req, res, next) => {\n  const allTodos: Todos[] = await Todos.findAll();\n  return res\n    .status(200)\n    .json({ message: \"Todo fetched successfully\", data: allTodos });\n};\n\nexport const getTodoById: RequestHandler = async (req, res, next) => {\n  const { id } = req.params;\n  const todos: Todos | null = await Todos.findByPk(id);\n  return res\n    .status(200)\n    .json({ message: \"Todo fetched successfully\", data: todos });\n};\n\nexport const updateTodo: RequestHandler = async (req, res, next) => {\n  const { id } = req.params;\n  await Todos.update({ ...req.body }, { where: { id } });\n  const updatedTodos: Todos | null = await Todos.findByPk(id);\n  return res\n    .status(200)\n    .json({ message: \"Todo updated successfully\", data: updatedTodos });\n};\n</code></pre>\n<p><strong><em>Create a folder name routes inside src folder and create a file name todos.ts</em></strong> which is route file and copy paste below code</p>\n<pre><code class=\"language-js\">import { Router } from \"express\";\n\nimport {\n  createToDo,\n  deleteToDo,\n  getAllToDo,\n  updateTodo,\n  getTodoById,\n} from \"../controllers/todos\";\n\nconst router = Router();\n\nrouter.post(\"/\", createToDo);\n\nrouter.get(\"/\", getAllToDo);\n\nrouter.get(\"/:id\", getTodoById);\n\nrouter.put(\"/:id\", updateTodo);\n\nrouter.delete(\"/:id\", deleteToDo);\n\nexport default router;\n</code></pre>\n<p><strong><em>Create a folder name models inside src folder and create a file name todos.ts</em></strong> which is model file and copy paste below code</p>\n<pre><code class=\"language-js\">import { Table, Model, Column, DataType } from \"sequelize-typescript\";\n\n@Table({\n  timestamps: false,\n  tableName: \"todos\",\n})\nexport class Todos extends Model {\n  @Column({\n    type: DataType.STRING,\n    allowNull: false,\n  })\n  name!: string;\n\n  @Column({\n    type: DataType.STRING,\n    allowNull: false,\n  })\n  description!: string;\n}\n</code></pre>\n<p><strong><em>Create sequelize database connection file config.ts inside db folder under root path</em></strong> and copy paste below code</p>\n<pre><code class=\"language-js\">import { Sequelize } from \"sequelize-typescript\";\nimport { Todos } from \"../models/todos\";\n\nconst connection = new Sequelize({\n  dialect: \"mysql\",\n  host: \"localhost\",\n  username: \"root\",\n  password: \"anku@1234\",\n  database: \"todos\",\n  logging: false,\n  models: [Todos],\n});\n\nexport default connection;\n</code></pre>\n<p><strong><em>Update your app.ts file</em></strong> with below code this includes connection code with mongodb and routes code</p>\n<pre><code class=\"language-js\">import express from \"express\";\nimport todoRoutes from \"./routes/todos\";\nimport connection from \"./db/config\";\nimport { json, urlencoded } from \"body-parser\";\n\nconst app = express();\n\napp.use(json());\n\napp.use(urlencoded({ extended: true }));\n\napp.use(\"/todos\", todoRoutes);\n\napp.use(\n  (\n    err: Error,\n    req: express.Request,\n    res: express.Response,\n    next: express.NextFunction\n  ) => {\n    res.status(500).json({ message: err.message });\n  }\n);\n\nconnection\n  .sync()\n  .then(() => {\n    console.log(\"Database successfully connected\");\n  })\n  .catch((err) => {\n    console.log(\"Error\", err);\n  });\napp.listen(3000, () => {\n  console.log(\"Server started on port 3000\");\n});\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-sequelize-typescript-6.png\" alt=\"folderstructure\"></p>\n<p><strong><em>Test your REST API with postman</em></strong></p>\n<p>Open postman and also make sure that your <strong><em>mysql server on your local computer is running</em></strong></p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-sequelize-typescript-7.png\" alt=\"postman\"></p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-sequelize-typescript-8.png\" alt=\"mysqlworkbench\"></p>","fields":{"slug":"/node-express-typescript-sequelize-mysql-rest-api/"},"frontmatter":{"title":"Developing REST Api using sequelize typescript, node, express and mysql","date":"December 10, 2022","description":"In this article i will explain you step by step to setup REST Api with node, express, mysql, sequelize and typescript","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/RestAPI.jpg"}},"previous":{"fields":{"slug":"/node-express-typescript-mongo-rest-api/"},"frontmatter":{"title":"Developing REST Api using typescript, node, express and mongodb","date":"December 03, 2022","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/RestAPI.jpg"}},"next":{"fields":{"slug":"/package-nodejs-application-using-webpack/"},"frontmatter":{"title":"How to package nodejs application using webpack","date":"December 15, 2022","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/nodejs-webpack.jpeg"}}},"pageContext":{"id":"03f05a1d-ad5f-5c4b-a5d2-d6a02f510ad8","previousPostId":"39dc311c-1ef8-5938-a4aa-60266cea747e","nextPostId":"7702ffd3-33a4-5338-b1b1-356a66dc22c8"}},
    "staticQueryHashes": ["3860684146"]}