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

  • 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. 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. 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 http module is crucial for creating the server and managing HTTP requests and responses in a vanilla Node.js REST API.

    Explanation

    The http module 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. 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. 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.json file 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. 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. 6

    Which npm package is used as a development dependency to automatically restart the server upon file changes?

    Model answer

    The nodemon npm package is used as a development dependency to automatically restart the server when file changes are detected.

    Explanation

    nodemon is 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. 7

    Explain the difference between npm start and npm run dev scripts as configured in the package.json for this project.

    Model answer

    npm start runs the node server.js command, typically used for deployment, while npm run dev uses nodemon server.js to enable automatic server restarts during development.

    Explanation

    The start script is designed for production environments where the server is expected to run continuously without frequent restarts. The dev script, leveraging nodemon, is tailored for development, providing convenience by automatically reloading the server whenever code changes are saved, improving efficiency.

  8. 8

    What is the significance of process.env.PORT || 5000 when defining the server's port?

    Model answer

    process.env.PORT || 5000 means the server will listen on the port specified by the PORT environment 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 PORT environment variable. By checking process.env.PORT, the application can adapt to the assigned port, while || 5000 provides a convenient default for local development.

  9. 9

    How do you set an HTTP status code and a Content-Type header using the res object in a vanilla Node.js HTTP response?

    Model answer

    You can set the status code using res.writeHead(statusCode, headersObject) and specify the Content-Type within the headersObject, 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. 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 the res.end() or res.write() methods expect a string or a buffer, and JSON.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. 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.url property is used for the requested URL, and req.method is used for the HTTP method.

    Explanation

    In a vanilla Node.js http.createServer callback, the request object provides essential information about the incoming client request. req.url contains the path and query string (e.g., /api/products?limit=10), while req.method contains the HTTP verb (e.g., 'GET', 'POST', 'PUT', 'DELETE'). These are fundamental for manual routing.

  12. 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. 13

    Why do the model functions, such as findAll and findById, return a Promise in this vanilla Node.js API?

    Model answer

    Model functions return a Promise to 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. 14

    When defining a route for a single product using its ID (e.g., /api/products/1), how is the ID extracted from req.url in a vanilla Node.js API without Express's req.params?

    Model answer

    The ID is extracted from req.url by 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.params is an Express feature, a vanilla Node.js application must manually parse the URL. By splitting req.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. 15

    What is the purpose of the uuid npm package, and how is it used in the product-model.js file?

    Model answer

    The uuid npm package is used to generate universally unique identifiers (UUIDs) for new products. In product-model.js, v4() from uuid is 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. 16

    Explain the role of utils.js and the writeDataToFile function in the context of this API.

    Model answer

    The utils.js file contains helper functions like writeDataToFile, 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, the product-model.js remains cleaner and focused on data manipulation. writeDataToFile uses Node.js's fs.writeFileSync to update the products.json file, converting the JavaScript array of products back into a JSON string before writing, thereby saving the current state of products.

  17. 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. Once req.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. The data event emits Buffer objects as parts of the body arrive, which must be converted to strings and appended. The end event signifies the completion of the body stream, at which point the full body string can be JSON.parsed for use.

  18. 18

    How does the getPostData utility function simplify handling POST request body data compared to doing it manually in each controller?

    Model answer

    The getPostData utility function encapsulates the complex req.on('data') and req.on('end') event handling into a promise, allowing controllers to await a single function call to receive the parsed body data, making the controller code much cleaner.

    Explanation

    By returning a Promise, getPostData abstracts away the event-driven nature of stream processing. Controllers can simply await 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. 19

    When performing an update operation (PUT request), how does the updateProduct controller ensure that partial updates are handled correctly without overwriting unspecified fields?

    Model answer

    The updateProduct controller handles partial updates by setting each field (title, description, price) to either the value provided in the request body or its existing value from the product.title, product.description, or product.price.

    Explanation

    This approach is crucial for PATCH or PUT requests that allow partial modifications. By using body.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. 20

    In the remove function within product-model.js, how does products.filter() achieve the deletion of a specific product?

    Model answer

    The products.filter() method creates a new array containing all products whose id does not match the id of 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 returns true. By checking p.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 old products array.

1 of 20
Question 1 of 20

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent