{
    "componentChunkName": "component---src-templates-blog-post-js",
    "path": "/node-express-typescript-mongo-rest-api/",
    "result": {"data":{"site":{"siteMetadata":{"title":"CrewCode Solutions"}},"markdownRemark":{"id":"39dc311c-1ef8-5938-a4aa-60266cea747e","excerpt":"In this article i will explain you step by step to setup REST Api with node, express , mongodb and typescript Step 1: Install typescript globally We need to…","html":"<p>In this article i will explain you step by step to setup REST Api with node, express , mongodb 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-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-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-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-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 mongoose\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-typescript-5.png\" alt=\"npm-start\"></p>\n<h4>Step 7: Creating routes, controller , model folder, connecting to mongodb 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 Todo, { TodoModel } from \"../models/todos\";\n\nexport const createToDo: RequestHandler = async (req, res, next) => {\n  try {\n    const data: TodoModel = req.body;\n    console.log(\"Data\", data);\n    var todos = await Todo.create(data);\n    return res\n      .status(200)\n      .json({ message: \"Todo created successfully\", data: todos });\n  } catch (error: any) {\n    return res.status(500).json({ message: error.message });\n  }\n};\n\nexport const getToDo: RequestHandler = async (req, res, next) => {\n  try {\n    var todos = await Todo.find({});\n    return res.status(200).json({ message: \"All todos!\", data: todos });\n  } catch (error: any) {\n    return res.status(500).json({ message: error.message });\n  }\n};\n\nexport const updateToDo: RequestHandler = async (req, res, next) => {\n  try {\n    const { id } = req.params;\n    var todos = await Todo.findByIdAndUpdate(id, req.body, { new: true });\n    return res\n      .status(200)\n      .json({ message: \"Todo updated successfully!\", data: todos });\n  } catch (error: any) {\n    return res.status(500).json({ message: error.message });\n  }\n};\n\nexport const deleteToDo: RequestHandler = async (req, res, next) => {\n  try {\n    const { id } = req.params;\n    var isDeleted = await Todo.findByIdAndDelete(id);\n    if (!isDeleted) throw new Error(\"Failed to delete todo\");\n    return res.status(200).json({ message: \"Todo deleted successfully!\" });\n  } catch (error: any) {\n    return res.status(500).json({ message: error.message });\n  }\n};\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\";\nimport {\n  createToDo,\n  getToDo,\n  updateToDo,\n  deleteToDo,\n} from \"../controllers/todos\";\n\nconst router = Router();\n\nrouter.post(\"/\", createToDo);\n\nrouter.get(\"/\", getToDo);\n\nrouter.patch(\"/: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 * as mongoose from \"mongoose\";\nimport { Model } from \"mongoose\";\n\ntype TodoType = TodoModel &#x26; mongoose.Document;\nexport interface TodoModel {\n  title: {\n    type: String,\n    required: true,\n  };\n  description: {\n    type: String,\n    required: true,\n  };\n}\nconst TodosSchema = new mongoose.Schema({\n  title: {\n    type: String,\n    required: true,\n  },\n  description: {\n    type: String,\n    required: true,\n  },\n});\nconst Todo: Model&#x3C;TodoType> = mongoose.model &#x3C; TodoType > (\"Todo\", TodosSchema);\nexport default Todo;\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 db from \"mongoose\";\nimport todoRoutes from \"./routes/todos\";\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\ndb.connect(\"mongodb://localhost:27017/todos\", () => {\n  console.log(\"Database connected\");\n});\n\napp.listen(3000);\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-rest-api-typescript-6.png\" alt=\"npm-start\"></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>mongodb 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-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-typescript-8.png\" alt=\"postman-get\"></p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-rest-api-typescript-9.png\" alt=\"postman-patch\"></p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-rest-api-typescript-10.png\" alt=\"postman-delete\"></p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-rest-api-typescript-11.png\" alt=\"mongodb\"></p>","fields":{"slug":"/node-express-typescript-mongo-rest-api/"},"frontmatter":{"title":"Developing REST Api using typescript, node, express and mongodb","date":"December 03, 2022","description":"In this article i will explain you step by step to setup REST Api with node, express, mongodb and typescript","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/RestAPI.jpg"}},"previous":{"fields":{"slug":"/mqtt-in-nodejs/"},"frontmatter":{"title":"MQTT in NodeJS application","date":"November 28, 2022","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/mqtt-nodejs.jpeg"}},"next":{"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","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/RestAPI.jpg"}}},"pageContext":{"id":"39dc311c-1ef8-5938-a4aa-60266cea747e","previousPostId":"70d3a11a-670c-5a46-8f08-68f675fa722c","nextPostId":"03f05a1d-ad5f-5c4b-a5d2-d6a02f510ad8"}},
    "staticQueryHashes": ["3860684146"]}