{"componentChunkName":"component---src-templates-post-template-js","path":"/posts/create-a-todo-api-using-express","result":{"data":{"mdx":{"frontmatter":{"title":"Create A Todo API Using Express","category":"Express","date":"July 8th, 2020","readTime":6,"slug":"create-a-todo-api-using-express","embeddedImages":[{"childImageSharp":{"gatsbyImageData":{"layout":"constrained","backgroundColor":"#282838","images":{"fallback":{"src":"/static/e004df04fb0fcc2e6c0631d80a329f20/b2dda/op1.png","srcSet":"/static/e004df04fb0fcc2e6c0631d80a329f20/9967c/op1.png 288w,\n/static/e004df04fb0fcc2e6c0631d80a329f20/6b282/op1.png 577w,\n/static/e004df04fb0fcc2e6c0631d80a329f20/b2dda/op1.png 1153w","sizes":"(min-width: 1153px) 1153px, 100vw"},"sources":[{"srcSet":"/static/e004df04fb0fcc2e6c0631d80a329f20/cc38b/op1.webp 288w,\n/static/e004df04fb0fcc2e6c0631d80a329f20/b0115/op1.webp 577w,\n/static/e004df04fb0fcc2e6c0631d80a329f20/b5a75/op1.webp 1153w","type":"image/webp","sizes":"(min-width: 1153px) 1153px, 100vw"}]},"width":1153,"height":646}}},{"childImageSharp":{"gatsbyImageData":{"layout":"constrained","backgroundColor":"#282838","images":{"fallback":{"src":"/static/286eb7e89bce53eb0c904c220a9f92e2/e8534/op2.png","srcSet":"/static/286eb7e89bce53eb0c904c220a9f92e2/09bb1/op2.png 281w,\n/static/286eb7e89bce53eb0c904c220a9f92e2/270b9/op2.png 562w,\n/static/286eb7e89bce53eb0c904c220a9f92e2/e8534/op2.png 1123w","sizes":"(min-width: 1123px) 1123px, 100vw"},"sources":[{"srcSet":"/static/286eb7e89bce53eb0c904c220a9f92e2/7f0cb/op2.webp 281w,\n/static/286eb7e89bce53eb0c904c220a9f92e2/a3491/op2.webp 562w,\n/static/286eb7e89bce53eb0c904c220a9f92e2/93831/op2.webp 1123w","type":"image/webp","sizes":"(min-width: 1123px) 1123px, 100vw"}]},"width":1123,"height":631}}},{"childImageSharp":{"gatsbyImageData":{"layout":"constrained","backgroundColor":"#282838","images":{"fallback":{"src":"/static/f8513204c1dd692d73eca63f2b16997f/55b4c/op3.png","srcSet":"/static/f8513204c1dd692d73eca63f2b16997f/abdb4/op3.png 277w,\n/static/f8513204c1dd692d73eca63f2b16997f/41626/op3.png 554w,\n/static/f8513204c1dd692d73eca63f2b16997f/55b4c/op3.png 1107w","sizes":"(min-width: 1107px) 1107px, 100vw"},"sources":[{"srcSet":"/static/f8513204c1dd692d73eca63f2b16997f/a02fd/op3.webp 277w,\n/static/f8513204c1dd692d73eca63f2b16997f/7abf3/op3.webp 554w,\n/static/f8513204c1dd692d73eca63f2b16997f/8e084/op3.webp 1107w","type":"image/webp","sizes":"(min-width: 1107px) 1107px, 100vw"}]},"width":1107,"height":622}}}],"image":{"childImageSharp":{"gatsbyImageData":{"layout":"constrained","backgroundColor":"#282838","images":{"fallback":{"src":"/static/e004df04fb0fcc2e6c0631d80a329f20/b2dda/op1.png","srcSet":"/static/e004df04fb0fcc2e6c0631d80a329f20/9967c/op1.png 288w,\n/static/e004df04fb0fcc2e6c0631d80a329f20/6b282/op1.png 577w,\n/static/e004df04fb0fcc2e6c0631d80a329f20/b2dda/op1.png 1153w","sizes":"(min-width: 1153px) 1153px, 100vw"},"sources":[{"srcSet":"/static/e004df04fb0fcc2e6c0631d80a329f20/cc38b/op1.webp 288w,\n/static/e004df04fb0fcc2e6c0631d80a329f20/b0115/op1.webp 577w,\n/static/e004df04fb0fcc2e6c0631d80a329f20/b5a75/op1.webp 1153w","type":"image/webp","sizes":"(min-width: 1153px) 1153px, 100vw"}]},"width":1153,"height":646}}}},"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsxRuntime classic */\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Create A Todo API Using Express\",\n  \"slug\": \"create-a-todo-api-using-express\",\n  \"image\": \"./images/op1.png\",\n  \"date\": \"2020-07-08T00:00:00.000Z\",\n  \"category\": \"Express\",\n  \"readTime\": 6,\n  \"embeddedImages\": [\"./images/op1.png\", \"./images/op2.png\", \"./images/op3.png\"]\n};\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"p\", null, \"In this tutorial, I will show how to make an API with the express which is actually a javascript framework.\"), mdx(\"p\", null, \"So let's get started\"), mdx(\"p\", null, \"First of all, make sure you have set up \", mdx(\"a\", {\n    href: \"https://nodejs.org/en/\",\n    target: \"_blank\"\n  }, \"Node Js\"), \" in your local pc, this tutorial I'm going to use \", mdx(\"a\", {\n    href: \"https://code.visualstudio.com/download\",\n    target: \"_blank\"\n  }, \"VS code editor\"), \" , make sure it also has in your local pc.\"), mdx(\"p\", null, \"First, make a project folder like \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"todos_api\"), \" then open it with your vs code editor\"), mdx(\"p\", null, \"Then do\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"git init -y\\n\")), mdx(\"p\", null, \"For initial your project, it will make a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"package.json\"), \" file in your project directory, after that \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"install\"), \" two package in your root project directory.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"npm install express\\nnpm install shortid\\n\")), mdx(\"p\", null, \"After that you should see in your \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"package.json\"), \" file like:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"{\\n  \\\"name\\\": \\\"basic_express\\\",\\n  \\\"version\\\": \\\"1.0.0\\\",\\n  \\\"description\\\": \\\"\\\",\\n  \\\"main\\\": \\\"index.js\\\",\\n  \\\"scripts\\\": {\\n    \\\"test\\\": \\\"echo \\\\\\\"Error: no test specified\\\\\\\" && exit 1\\\",\\n    \\\"start\\\": \\\"nodemon index.js\\\"\\n  },\\n  \\\"keywords\\\": [],\\n  \\\"author\\\": \\\"\\\",\\n  \\\"license\\\": \\\"ISC\\\",\\n  \\\"dependencies\\\": {\\n    \\\"express\\\": \\\"^4.17.1\\\",\\n    \\\"shortid\\\": \\\"^2.2.16\\\"\\n  }\\n}\\n\\n\")), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"nodemon index.js\"), \" for this line make sure you have install nodemon, it should be global or in your local project directory and make a file called \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"index.js\"), \" in your project root directory\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"# Install nodemon\\nnpm install nodemon\\n\\n# Install nodemon globally on your machine\\nnpm install -g nodemon\\n\\n# Install nodemon on your project as dev-dependency\\nnpm install nodemon --save-dev\\n\")), mdx(\"h3\", null, \"File Directory\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-file\"\n  }, \"> |> node_modules\\n> |.gitignore\\n> |controller.js\\n> |index.js\\n> |package-lock.json\\n> |package.json\\n> |routes.js\\n\")), mdx(\"p\", null, \"Then make a simple server with express js\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"const express = require('express')\\n\\nconst app = express()\\napp.use(express.json())\\n\\napp.get('/', (req, res) => {\\n  res.send('I am alive')\\n})\\n\\napp.listen(4000, () => {\\n  console.log('Server is running on port 4000')\\n})\\n\")), mdx(\"p\", null, \"Now if you run \", mdx(\"a\", {\n    href: \"http://localhost:4000/\"\n  }, \"localhost:4000\"), \" then you should see the output in the browser \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"I am alive\")), mdx(\"p\", null, \"This project is about to Create, Read, Update and delete (CRUD) application\"), mdx(\"div\", {\n    className: \"code\"\n  }, mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-note\"\n  }, \"/**\\n * HTTP Verbs or Methods\\n * - GET (get a list of data or single object of data)\\n * - POST (create new resources)\\n * - PUT (Update -> whole object)\\n * - PATCH (Update -> update specific propertices)\\n * - DELETE (Delete the resource)\\n *\\n * Resource URI\\n *  - GET (/todos)\\n *  - POST (/todos)\\n *  - GET (/todos/todosId)\\n *  - PUT/PATCH (/todos/todosId)\\n *  - DELETE (/todos/todosId)\\n */\\n\"))), mdx(\"p\", null, \"For more please read from \", mdx(\"a\", {\n    href: \"https://www.restapitutorial.com/\",\n    target: \"_blank\"\n  }, \"here\")), mdx(\"h2\", null, \"Create a Todo list\"), mdx(\"p\", null, \"First of all, we will create a todo list with \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"post\"), \" request controller\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"routes.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"const router = require('express').Router()\\nconst controller = require('./controllers')\\n\\nrouter.post('/', controller.create)\\n\\nmodule.exports = router\\n\")), mdx(\"p\", null, \"Here, actually I have make a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"routes\"), \" which is connected with a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"create\"), \" controller,\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"controllers.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"var shortid = require('shortid')\\nconst todos = []\\n\\nexports.create = (req, res) => {\\n  const { text } = req.body\\n  const todo = {\\n    id: shortid(),\\n    text,\\n    isCompleted: false,\\n    created: new Date(),\\n  }\\n\\n  todos.push(todo)\\n\\n  res.status(201).json({ message: 'todos created succesful', ...todo })\\n}\\n\")), mdx(\"p\", null, \"Now we have \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"routes\"), \" and \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"controllers\"), \" but still our project will not run, because still we didn't connect our project with our main root file which will render from \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"index.js\"), \" file, so let's update our \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"index\"), \" file.\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"index.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"const express = require('express')\\n\\nconst app = express()\\napp.use(express.json())\\n\\napp.use('/todos', require('./routes'))\\n\\napp.get('/', (req, res) => {\\n  res.send('I am alive')\\n})\\n\\napp.listen(4000, () => {\\n  console.log('Server is running on port 4000')\\n})\\n\")), mdx(\"p\", null, \"just add \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"app.use(\\\"/todos\\\", require(\\\"./routes\\\"));\"), \" this line.\"), mdx(\"p\", null, \"In this article we will use \", mdx(\"a\", {\n    href: \"https://www.thunderclient.io/\",\n    target: \"_blank\"\n  }, \"thunderclient\"), \" for check our API, it's a VS code extension you can add from here or you can manually add from your VS code extension tab.\"), mdx(\"p\", null, \"Upto this point if everything is ok, then open your thunderclient and tab on new button then you need to input your current localhost address which you had use in your project \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"localhost:4000\"), \", remember your initial routes starts with \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"/todos\"), \", so your address will be \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"localhost:4000/todos\"), \" then in the body section required a text, after doing this tab on the send button, then you mayb see\"), mdx(GatsbyImage, {\n    image: getImage(props.embeddedImages[0]),\n    alt: \"random stuff\",\n    className: \"first-inline-img\",\n    mdxType: \"GatsbyImage\"\n  }), mdx(\"p\", null, \"Now I'm going to add all routes which will be include in our project which is \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"GET\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"POST\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"PUT\"), \" and \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"PATCH\")), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"routes.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"const router = require('express').Router()\\nconst controller = require('./controllers')\\n\\nrouter.delete('/:todoId', controller.deleteTodos)\\nrouter.patch('/:todoId', controller.patchUpdateById)\\nrouter.put('/:todoId', controller.putUpdateById)\\nrouter.get('/:todoId', controller.findById)\\nrouter.get('/', controller.findAll)\\nrouter.post('/', controller.create)\\n\\nmodule.exports = router\\n\")), mdx(\"h2\", null, \"Find All todos\"), mdx(\"p\", null, \"It should be a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"get\"), \" request which will show all data, that we already had import data with the \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"post\"), \" request.\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"controllers.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"var shortid = require('shortid')\\nconst todos = []\\n\\nexports.findAll = (req, res) => {\\n  const result = todos.map(todo => ({ id: todo.id, text: todo.text }))\\n  return res.status(200).json(result)\\n}\\n\")), mdx(\"p\", null, \"I just added content three more times with the post request, now if you want to see all data then just select \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"get\"), \" request with the same routes which is \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"localhost:4000/todos\"), \" (\", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"GET\"), \" request)\"), mdx(GatsbyImage, {\n    image: getImage(props.embeddedImages[1]),\n    alt: \"random stuff\",\n    className: \"first-inline-img\",\n    mdxType: \"GatsbyImage\"\n  }), mdx(\"h2\", null, \"Find todos by id\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"controllers.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"var shortid = require('shortid')\\nconst todos = []\\n\\nexports.findById = (req, res) => {\\n  const { todoId } = req.params\\n  const todo = todos.find(todo => todo.id === todoId)\\n  return res.status(201).json(todo)\\n}\\n\")), mdx(\"p\", null, \"When we have created a todos with the \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"post\"), \" request then we have seen, that we have imported data like \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"text\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"shortid\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"isCompleted\"), \" (which is default \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"false\"), \"), \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"Date\"), \", we can't seen those data in the get request when we had to find all data, because I have find just \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"text\"), \" and \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"id\"), \", but in the \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"findById\"), \" routes we have find all information from our ontime database.\"), mdx(\"p\", null, \"Then our output should be\"), mdx(GatsbyImage, {\n    image: getImage(props.embeddedImages[2]),\n    alt: \"random stuff\",\n    className: \"first-inline-img\",\n    mdxType: \"GatsbyImage\"\n  }), mdx(\"h2\", null, \"Update todo by PUT request\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"controllser.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"var shortid = require('shortid')\\nconst todos = []\\n\\nexports.putUpdateById = (req, res) => {\\n  // if the item is not exist the then create one\\n  // if it exist then update\\n  const { text, isCompleted } = req.body\\n  const { todoId } = req.params\\n  const todo = todos.find(todo => todo.id === todoId)\\n\\n  if (!todo) {\\n    // will be new create\\n    const todo = {\\n      id: shortid(),\\n      text,\\n      isCompleted: false,\\n      created: new Date(),\\n    }\\n    todos.push(todo)\\n    res.status(201).json({ message: 'updated new todos created', ...todo })\\n  } else {\\n    // update\\n    ;(todo.text = text || todo.text),\\n      (todo.isCompleted = isCompleted || todo.isCompleted)\\n\\n    const index = todos.findIndex(todo => todo.id === todoId)\\n\\n    todos[index] = todo\\n    res.status(201).json({ message: 'todos updated', ...todo })\\n  }\\n}\\n\")), mdx(\"p\", null, \"In the put or update request first we have to verify the \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"id\"), \" if id match with the current content then just go with else condition and update our old todos then save it with todos array, but if we do not find any todos with that id then just make a new todos with unknown id, you should run and check this one.\"), mdx(\"h2\", null, \"update todos with patch request\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"controllers.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"var shortid = require('shortid')\\nconst todos = []\\n\\nexports.patchUpdateById = (req, res) => {\\n  const { todoId } = req.params\\n  const { text, isCompleted } = req.body\\n\\n  const index = todos.findIndex(todo => todo.id === todoId)\\n\\n  if (index === -1) {\\n    return res.status(404).json({ message: 'Todo not found' })\\n  }\\n  todos[index].text = text || todos[index].text\\n  todos[index].isCompleted = isCompleted || todos[index].isCompleted\\n\\n  res.status(201).json({ message: 'Todo updated succesfully', ...todos[index] })\\n}\\n\")), mdx(\"p\", null, \"In this patch request first of all check the id and remember it will check with the value of the index, if find the id then just update the index number or show the message \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"Todo not found\"), \", please check and run it, if you faced any problem then write in the comment box about your problem.\"), mdx(\"h2\", null, \"Delete todos\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"controllers.js\")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"var shortid = require('shortid')\\nconst todos = []\\n\\nexports.deleteTodos = (req, res) => {\\n  const { todoId } = req.params\\n  const index = todos.findIndex(todo => todo.id === todoId)\\n  todos.slice(index, 1)\\n}\\n\")), mdx(\"p\", null, \"Delete routes will delete the whole resources with find the todos id then just slice index number.\"), mdx(Link, {\n    to: \"/posts\",\n    className: \"btn center-btn\",\n    mdxType: \"Link\"\n  }, \"all posts\"));\n}\n;\nMDXContent.isMDXComponent = true;","id":"c85ea687-2a23-52f7-b2ee-cd459a735c62"}},"pageContext":{"slug":"create-a-todo-api-using-express"}},"staticQueryHashes":["3361116154","3824322444"]}