1. Home
  2. Explore
  3. Computer Science
  4. Node.js REST API

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Node.js REST API

Speaker 1Speaker 2

Node.js REST API

13:13
0:00-13:13
  1. Simon

    Hey Corey, welcome to the podcast! Today we're diving into creating a vanilla Node.js REST API, complete with full CRUD functionality. That means we'll cover how to create, read, update, and delete data from a JSON file. Sounds like a fun challenge, right?

  2. Corey

    Absolutely, Simon! It's great to be here. This is an interesting approach because usually, when people talk about Node APIs, Express.js is the first thing that comes to mind. But we're going bare-bones, just using Node's built-in HTTP module, which I think is a fantastic way to learn the fundamentals.

  3. Simon

    Exactly. It's definitely harder to write without all the conveniences of a framework like Express, but it offers such a deep learning experience. We'll really get into the nitty-gritty of the HTTP request-response cycle and how to structure our code with controllers and models.

  4. Corey

    That's a key point. We'll have to manually figure out which route is being hit, which HTTP method is being used, and handle all the request parsing ourselves. It's more work, but it really clarifies what Express and other frameworks do for us under the hood, making them so powerful.

  5. Simon

    For sure. So, to kick things off, you'll obviously need Node.js installed. If you're new to Node, I'd suggest checking out a crash course first. And, to test our API, we'll be using Postman, which you can grab from postman.com if you don't already have it.

  6. Corey

    Good call on Postman; it's essential for API development. As for our project setup, I've got a folder called 'vanilla-node-rest-api' with a 'data' folder inside. In 'data', there's a 'products.json' file containing five products, each with an ID, name, description, and price.

  7. Simon

    Right, and we'll be reading from and writing to that JSON file. While you could use a database, sticking with a JSON file simplifies things for this tutorial, and it means we'll be leveraging Node's built-in File System module, which is perfect for this kind of interaction.

  8. Corey

    Okay, so let's start by initializing our project. We'll run npm init -y to quickly create a package.json file. For third-party packages, the only one we'll be using is Nodemon. It's a lifesaver for development as it automatically restarts the server when files change.

  9. Simon

    Right, so that's npm install --save-dev nodemon. And then we'll add two scripts to our package.json: a 'start' script for 'node server.js' and a 'dev' script for 'nodemon server.js'. This lets us easily run our server in development with automatic restarts.

  10. Corey

    Perfect. Once that's set up, we'll create our 'server.js' file, which is the entry point. We need to bring in Node's native 'http' module. This module is the foundation that frameworks like Express build upon, providing the core functionality for handling network requests.

  11. Simon

    Exactly. The http module has a 'createServer' method, which takes a function with 'req' and 'res' objects. These objects allow us to access request data like the URL and method, and to send responses with specific headers and body content. It's the core of everything.

  12. Corey

    Then, we call .listen on our server instance, passing in a port number. I usually define a PORT variable that checks for an environment variable first, like process.env.PORT, defaulting to 5000 if not found. We also add a console log to confirm the server's running.

  13. Simon

    So, if we run 'npm run dev' now, Nodemon watches 'server.js', and we'll see 'Server running on port 5000'. If we hit 'localhost:5000' in Postman, it just hangs because we haven't actually responded with anything yet inside our 'createServer' function. It's just logging for now.

  14. Corey

    To give a generic response, we first set the response status code, like 200 for success. Then, we set the 'Content-Type' header using 'res.setHeader'. For HTML, it'd be 'text/html'. Finally, 'res.write' sends the body, and 'res.end' closes the connection.

  15. Simon

    Right, so if we send back '<h1>Hello World</h1>' with 'text/html', the browser renders it. Postman shows the 200 status and the correct content type in the headers. It's a simple example, but it demonstrates the basic request-response cycle we need to manage.

  16. Corey

    Now, instead of HTML, we want to send our products. We'll 'require' our 'products.json' file. To simplify the response, we can use 'res.writeHead(200, { 'Content-Type': 'application/json' })' and then 'res.end(JSON.stringify(products))' to send the JSON.

  17. Simon

    That's a good simplification. Remember, even though we're requiring a '.json' file, it comes in as a JavaScript array, so we must explicitly use 'JSON.stringify()' before sending it. Express handles this for us, but here, we do it manually, which is a great learning point.

  18. Corey

    Even with this, if we make a GET request to '/api/products', it works, but it also works for '/api/anything' or even a POST request to '/api/products'. We need to add logic to check the URL and the HTTP method. This is where things get interesting without Express.

  19. Simon

    Exactly. So, we'll add an 'if' statement checking 'req.url === '/api/products'' AND 'req.method === 'GET''. Inside that, we'll put our code to send the products. Otherwise, in an 'else' block, we'll send a 404 'Not Found' response with a JSON message.

  20. Corey

    This manual routing is the core difference. If we request '/api/posts', we now get 'Route Not Found'. If we make a POST request to '/api/products', it also correctly returns 'Route Not Found'. This gives us precise control over what our API responds to.

  21. Simon

    Now, this is already getting a bit cluttered, and we'll have more routes for CRUD. So, let's clean this up using the Model-View-Controller pattern. We'll create a 'models' folder for 'product_model.js' and a 'controllers' folder for 'product_controller.js'.

  22. Corey

    The MVC pattern is perfect here. Since it's an API, no views are needed. Models will deal with our JSON file directly—getting, creating, updating, or deleting data. Controllers will handle the request/response logic, interacting with the models to fetch or manipulate data.

  23. Simon

    So, we'll move the 'products' import into 'product_model.js'. Then, in the model, we'll create an 'findAll' function that returns a new Promise, resolving with our 'products' array. We export this 'findAll' function so our controller can use it.

  24. Corey

    Then, in 'product_controller.js', we import our 'product_model'. We'll create an async 'getProducts' function, taking 'req' and 'res'. Inside a try-catch block, we 'await Product.findAll()', then send the products back with a 200 status and 'application/json' content type.

  25. Simon

    And finally, back in 'server.js', we destructure 'getProducts' from our 'product_controller' and call it in our '/api/products' GET route, passing in 'req' and 'res'. This modular structure keeps our 'server.js' clean and our concerns separated.

  26. Corey

    After fixing a quick export error in the controller, running this again gives us the exact same output in Postman as before, but our API's internal structure is now far superior. This separation of concerns will make adding more CRUD operations much easier.

  27. Simon

    Right. Next, let's implement getting a single product by ID. In Express, you'd use 'req.params.id', but here, we'll use a regular expression with 'req.url.match()' to extract the ID from a URL like '/api/products/1'.

  28. Corey

    So, we add an 'else if' block in 'server.js' that checks if 'req.url' matches '/api/products/\d+' (a digit) and 'req.method === 'GET''. We extract the ID by splitting 'req.url' and taking the last part. Then, we call a 'getProduct' controller function.

  29. Simon

    In 'product_controller.js', our async 'getProduct' function takes 'req', 'res', and 'id'. It calls 'await Product.findById(id)'. If no product is found, it sends a 404 with 'Product Not Found'. Otherwise, it sends the single product with a 200 status.

  30. Corey

    And in 'product_model.js', we create 'findById', which takes an 'id' and returns a Promise. It uses 'products.find(p => p.id === id)' to locate the product and then resolves the promise with that product. We ensure 'findById' is also exported.

  31. Simon

    Now, testing in Postman, '/api/products/1' fetches the first product, and '/api/products/22' correctly returns 'Product Not Found'. This demonstrates our manual routing and ID extraction working perfectly for individual resources.

  32. Corey

    Okay, time for the more complex part: creating a product with a POST request. In 'server.js', we'll add an 'else if' for 'req.url === '/api/products'' and 'req.method === 'POST''. If it matches, we'll call a 'createProduct' controller function.

  33. Simon

    In 'product_controller.js', our async 'createProduct' function takes 'req' and 'res'. For now, we'll hardcode a product object, say with 'title: Test Product', 'description', and 'price'. We'll use a 'Product.create()' model function and send back a 201 'Created' status.

  34. Corey

    To generate unique IDs for new products, we'll install 'uuid' (npm install uuid). In 'product_model.js', we import 'v4' from 'uuid'. Our 'create' function takes 'productData', adds a generated 'id' to it, pushes it to our 'products' array, and then saves it.

  35. Simon

    To save to the JSON file, we'll create a 'utils.js' file. It'll have a 'writeDataToFile' function that takes a 'filename' and 'content', then uses 'fs.writeFileSync' to write the 'JSON.stringify(content)' to the specified file. We export this function.

  36. Corey

    Then, in our 'product_model.js', we import 'writeDataToFile'. After adding the new product to the 'products' array, we call 'writeDataToFile()' to persist the changes. Finally, we resolve the promise with the new product data. Remember to export the 'create' function.

  37. Simon

    After exporting 'createProduct' in the controller, if we send a POST request to '/api/products' in Postman, we get a 201 status! Checking 'products.json', our new 'Test Product' is there, complete with a UUID. Now, let's fix the response so it sends the new product back.

  38. Corey

    Right, the controller needs to 'await' the 'Product.create()' call to get the returned new product. After fixing that, and optionally cleaning the 'products.json' file, resending the POST request successfully returns the newly created product in the response.

  39. Simon

    Now for the actual body data! We want to send raw JSON in our POST requests. This is where it gets a bit convoluted without Express. We have to manually listen for 'data' and 'end' events on the 'req' object to reconstruct the body string.

  40. Corey

    So, in 'createProduct', we initialize an empty 'body' string. We listen for 'req.on('data')', appending each 'chunk.toString()' to 'body'. Then, 'req.on('end')' is where we parse 'body' with 'JSON.parse()' and destructure the 'title', 'description', and 'price'.

  41. Simon

    This setup, while verbose, allows us to access the sent data. We pass these destructured values to our 'Product.create()' model function. We also need to make sure the 'await' for 'Product.create' is within the 'async' 'req.on('end')' callback, or label the callback as async.

  42. Corey

    This works, but that 'data' and 'end' event listening is something we'll need for updates too. So, let's refactor it into a utility function called 'getPostData' in 'utils.js'. It'll take 'req' and return a promise that resolves with the parsed body.

  43. Simon

    Yes, 'getPostData' will be async, returning a new Promise. Inside, it'll handle the 'req.on('data')' and 'req.on('end')' logic, accumulating the chunks and finally resolving the promise with the full body string. If there's an error, it rejects the promise.

  44. Corey

    Back in 'createProduct', we now just need 'const body = await getPostData(req);'. Then, we parse and destructure the 'title', 'description', and 'price' from 'body'. This makes our controller code much cleaner and more readable.

  45. Simon

    Awesome. With that, we can now send JSON data in our POST request to '/api/products'. The API successfully creates the product with the provided data and returns the new product in the response. We're making great progress!

  46. Corey

    Next up is updating a product, a PUT request to '/api/products/:id'. We'll add another 'else if' in 'server.js', similar to the GET by ID, but checking for 'req.method === 'PUT''. We extract the ID the same way and call an 'updateProduct' controller function.

  47. Simon

    Our 'updateProduct' controller function takes 'req', 'res', and 'id'. First, it 'awaits Product.findById(id)' to ensure the product exists. If not, it sends a 404. If it does, we then 'await getPostData(req)' to get the body for the update.

  48. Corey

    Then, we destructure the 'title', 'description', and 'price' from the body. We create a 'productData' object where each field is either the new value from the body or the existing product's value. This allows for partial updates.

  49. Simon

    Finally, we 'await Product.update(id, productData)', which will handle the actual update in the model. We send a 200 status code with the 'updatedProduct' as the response. Remember to export 'updateProduct' from the controller.

  50. Corey

    In 'product_model.js', our 'update' function takes 'id' and 'productData'. It finds the index of the product with that ID using 'products.findIndex()'. Then, it creates a new product object with the original ID and the updated data, spreading the new properties over the existing ones.

  51. Simon

    Then, we update the 'products' array at that index, call 'writeDataToFile()' to save the changes, and resolve the promise with the updated product. Make sure to export this 'update' function from the model.

  52. Corey

    Testing this out with Postman: a PUT request to '/api/products/:id' with a JSON body containing, say, just a new 'title', successfully updates only the title of that product and returns the updated product in the response. Checking the JSON file confirms the change.

  53. Simon

    Last but not least, the DELETE operation. Similar to getting a single product, we add another 'else if' in 'server.js' to match '/api/products/:id' but this time with 'req.method === 'DELETE''. We extract the ID and call a 'deleteProduct' controller function.

  54. Corey

    In 'product_controller.js', our 'deleteProduct' function takes 'req', 'res', and 'id'. It first checks if the product exists. If not, 404. If it does, it 'awaits Product.remove(id)' from the model, then sends a 200 status with a 'Product ID removed' message.

  55. Simon

    Finally, in 'product_model.js', our 'remove' function takes an 'id'. It reassigns the 'products' array by filtering out the product with the matching ID, effectively deleting it. Then, it 'writeDataToFile()' with the new array and resolves the promise.

  56. Corey

    With everything in place, if we make a DELETE request to '/api/products/:id', we get the success message. A subsequent GET request for that ID returns 'Product Not Found', and fetching all products confirms it's gone. We now have a fully functional vanilla Node.js REST API!

  57. Simon

    It was definitely more work than with Express, but hopefully, this deep dive into vanilla Node.js HTTP module, file system operations, and structuring an API with models and controllers provided some valuable learning. Thanks for joining me, Corey!

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent