Node.js REST API
- 20Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is the primary purpose of using the bare bones Node.js with the HTTP module instead of frameworks like Express for a REST API, as described in the video?
20 questions
- 1
What is the primary purpose of using the bare bones Node.js with the HTTP module instead of frameworks like Express for a REST API, as described in the video?
Model answer
The primary purpose is to gain a deeper understanding of the underlying HTTP request-response cycle and how Node.js handles core API functionalities manually, rather than relying on the abstractions provided by frameworks.
Explanation
Using bare bones Node.js with the HTTP module forces developers to manually handle aspects like routing, method checking, and data parsing, which are typically abstracted away by frameworks like Express. This process provides valuable insight into how web servers fundamentally operate and what frameworks do behind the scenes.
- 2
Which Node.js built-in module is crucial for creating the server and handling HTTP requests and responses in a vanilla Node.js REST API?
Model answer
The
httpmodule is crucial for creating the server and managing HTTP requests and responses in a vanilla Node.js REST API.Explanation
The
httpmodule is a core Node.js module that provides functionalities for creating HTTP servers and clients. It allows direct interaction with the HTTP protocol, enabling the creation of servers that listen for requests and send responses, forming the backbone of any web server built with Node.js. - 3
What are the four CRUD operations that the vanilla Node.js REST API developed in the video supports?
Model answer
The vanilla Node.js REST API supports Create, Read, Update, and Delete (CRUD) operations.
Explanation
CRUD stands for Create, Read, Update, and Delete. These are the four fundamental operations for persistent storage. The API developed in the video allows users to perform all these actions on product data, demonstrating a complete set of interactions with the data source.
- 4
Instead of a traditional database, what type of file is used for data storage and retrieval in this Node.js REST API?
Model answer
A JSON file (
products.json) is used for data storage and retrieval in this Node.js REST API.Explanation
The API utilizes a
products.jsonfile to store product data. This simplifies the setup by avoiding the need for a database, making it easier to focus on the core API logic and file system interactions using Node.js's built-in modules. - 5
What tool is recommended in the video for making requests to the API during development and testing?
Model answer
Postman is recommended for making requests to the API during development and testing.
Explanation
Postman is a popular API development environment that allows users to send various types of HTTP requests (GET, POST, PUT, DELETE) to an API endpoint, inspect responses, and manage request collections. It's an indispensable tool for testing RESTful APIs.
- 6
Which npm package is used as a development dependency to automatically restart the server upon file changes?
Model answer
The
nodemonnpm package is used as a development dependency to automatically restart the server when file changes are detected.Explanation
nodemonis a utility that monitors for any changes in your source and automatically restarts your server. This significantly enhances the development workflow by removing the manual step of stopping and starting the server after every code modification. - 7
Explain the difference between
npm startandnpm run devscripts as configured in thepackage.jsonfor this project.Model answer
npm startruns thenode server.jscommand, typically used for deployment, whilenpm run devusesnodemon server.jsto enable automatic server restarts during development.Explanation
The
startscript is designed for production environments where the server is expected to run continuously without frequent restarts. Thedevscript, leveragingnodemon, is tailored for development, providing convenience by automatically reloading the server whenever code changes are saved, improving efficiency. - 8
What is the significance of
process.env.PORT || 5000when defining the server's port?Model answer
process.env.PORT || 5000means the server will listen on the port specified by thePORTenvironment variable if it exists; otherwise, it will default to port 5000.Explanation
This common pattern allows for flexible deployment. In production environments, platforms often set a
PORTenvironment variable. By checkingprocess.env.PORT, the application can adapt to the assigned port, while|| 5000provides a convenient default for local development. - 9
How do you set an HTTP status code and a
Content-Typeheader using theresobject in a vanilla Node.js HTTP response?Model answer
You can set the status code using
res.writeHead(statusCode, headersObject)and specify theContent-Typewithin theheadersObject, for example,res.writeHead(200, { 'Content-Type': 'application/json' }).Explanation
The
res.writeHead()method allows you to send a response header to the request. It takes the status code as its first argument and an object containing header name-value pairs as the second. This method is essential for informing the client about the success or failure of the request and the format of the response body. - 10
Why is
JSON.stringify()necessary when sending a JavaScript object as a JSON response in a vanilla Node.js API?Model answer
JSON.stringify()is necessary because theres.end()orres.write()methods expect a string or a buffer, andJSON.stringify()converts a JavaScript object into a JSON formatted string.Explanation
HTTP responses are essentially streams of bytes. While JavaScript objects are convenient for programming logic, they cannot be directly sent over the network as-is.
JSON.stringify()serializes the JavaScript object into its JSON string representation, making it suitable for transmission in the HTTP response body. - 11
What are the request object properties used to determine the requested URL and HTTP method in a vanilla Node.js API?
Model answer
The
req.urlproperty is used for the requested URL, andreq.methodis used for the HTTP method.Explanation
In a vanilla Node.js
http.createServercallback, therequestobject provides essential information about the incoming client request.req.urlcontains the path and query string (e.g.,/api/products?limit=10), whilereq.methodcontains the HTTP verb (e.g., 'GET', 'POST', 'PUT', 'DELETE'). These are fundamental for manual routing. - 12
Explain the concept of Model-View-Controller (MVC) design pattern in the context of this API, specifically for the Model and Controller components.
Model answer
In this API, the Model (
product-model.js) handles data interactions, like reading from the JSON file, while the Controller (product-controller.js) manages request-response logic, interacts with the model, and determines the API's response.Explanation
The MVC pattern separates concerns: the Model is responsible for data logic (how data is stored and retrieved), and the Controller acts as an intermediary, processing incoming requests, coordinating with the model to fetch or manipulate data, and then preparing the appropriate response. Views are omitted as this is a REST API without a UI.
- 13
Why do the model functions, such as
findAllandfindById, return aPromisein this vanilla Node.js API?Model answer
Model functions return a
Promiseto simulate asynchronous data operations, even when interacting with a local file system, aligning with common patterns for database interactions.Explanation
While reading from a local JSON file is relatively fast and can be done synchronously, returning a promise makes the model functions consistent with how they would behave if they were interacting with a real database or an external API, which are inherently asynchronous operations. This design choice prepares the codebase for easier integration with actual databases in the future.
- 14
When defining a route for a single product using its ID (e.g.,
/api/products/1), how is the ID extracted fromreq.urlin a vanilla Node.js API without Express'sreq.params?Model answer
The ID is extracted from
req.urlby splitting the URL string by the/character and then accessing the appropriate index of the resulting array, typically the last element for an ID at the end of the path.Explanation
Since
req.paramsis an Express feature, a vanilla Node.js application must manually parse the URL. By splittingreq.url(e.g.,/api/products/123) into an array['', 'api', 'products', '123'], the ID ('123') can be retrieved from the last index ([3]). Regular expressions (.match()) can also be used to validate the URL pattern before extraction. - 15
What is the purpose of the
uuidnpm package, and how is it used in theproduct-model.jsfile?Model answer
The
uuidnpm package is used to generate universally unique identifiers (UUIDs) for new products. Inproduct-model.js,v4()fromuuidis called to assign a unique ID to each product upon creation.Explanation
UUIDs are 128-bit numbers used to uniquely identify information in computer systems. By using
uuid.v4(), the API ensures that every new product created has a distinct identifier, which is crucial for distinguishing between different products, especially in a file-based data store where auto-incrementing IDs might not be straightforward to implement. - 16
Explain the role of
utils.jsand thewriteDataToFilefunction in the context of this API.Model answer
The
utils.jsfile contains helper functions likewriteDataToFile, which is responsible for synchronously writing data (stringified JSON) to a specified file, ensuring data persistence after CUD operations.Explanation
By abstracting file-writing logic into
utils.js, theproduct-model.jsremains cleaner and focused on data manipulation.writeDataToFileuses Node.js'sfs.writeFileSyncto update theproducts.jsonfile, converting the JavaScript array of products back into a JSON string before writing, thereby saving the current state of products. - 17
Describe the process of handling incoming POST request body data in a vanilla Node.js API, including the events involved.
Model answer
Incoming POST request body data is handled by listening for
req.on('data')events, which receive data in chunks (buffers), and then concatenating these chunks into a string. Oncereq.on('end')fires, indicating all data has been received, the complete string body is parsed as JSON.Explanation
Unlike frameworks that provide
req.body, vanilla Node.js requires manual assembly of the request body. Thedataevent emitsBufferobjects as parts of the body arrive, which must be converted to strings and appended. Theendevent signifies the completion of the body stream, at which point the full body string can beJSON.parsed for use. - 18
How does the
getPostDatautility function simplify handling POST request body data compared to doing it manually in each controller?Model answer
The
getPostDatautility function encapsulates the complexreq.on('data')andreq.on('end')event handling into a promise, allowing controllers toawaita single function call to receive the parsed body data, making the controller code much cleaner.Explanation
By returning a
Promise,getPostDataabstracts away the event-driven nature of stream processing. Controllers can simplyawait getPostData(req), and once the promise resolves (when all data is received and concatenated), they get the complete request body string, which can then be parsed. This avoids repeating the verbose event listener setup in every controller that needs to read body data. - 19
When performing an update operation (
PUTrequest), how does theupdateProductcontroller ensure that partial updates are handled correctly without overwriting unspecified fields?Model answer
The
updateProductcontroller handles partial updates by setting each field (title, description, price) to either the value provided in the request body or its existing value from theproduct.title,product.description, orproduct.price.Explanation
This approach is crucial for
PATCHorPUTrequests that allow partial modifications. By usingbody.title || product.title, for example, the controller ensures that if a field is not present in the request body, its original value from the existing product data is retained, preventing unintended data loss for unspecified fields. - 20
In the
removefunction withinproduct-model.js, how doesproducts.filter()achieve the deletion of a specific product?Model answer
The
products.filter()method creates a new array containing all products whoseiddoes not match theidof the product to be removed, effectively excluding the target product from the collection.Explanation
The
filter()method iterates over an array and returns a new array containing only the elements for which the provided callback function returnstrue. By checkingp.id !== id, it keeps all products that are not the one to be deleted, thus achieving the deletion without directly mutating the original array, and then this new filtered array replaces the oldproductsarray.

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