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

  • 39Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: API Core Concepts

What is the primary purpose of this Node.js REST API tutorial?

39 questions

  1. 1

    What is the primary purpose of this Node.js REST API tutorial?

    1. A

      To build a full CRUD API using only the HTTP module without frameworks.

    2. B

      To explain how to integrate a database with a Node.js API project.

    3. C

      To teach basic Node.js syntax for front-end web development tasks.

    4. D

      To demonstrate the advantages of using Express.js for API development.

    Correct answer
    A

    To build a full CRUD API using only the HTTP module without frameworks.

    Explanation

    The tutorial explicitly states that its goal is to create a vanilla Node.js REST API with full CRUD functionality, using only bare bones Node with the HTTP module, deliberately avoiding frameworks like Express.

  2. 2

    Which of the following functionalities will the created API support?

    1. A

      Creation, reading, updating, and deleting of data records.

    2. B

      Server-side rendering of dynamic web pages for clients.

    3. C

      Integration with a NoSQL database like MongoDB for storage.

    4. D

      Real-time bidirectional communication using WebSockets.

    Correct answer
    A

    Creation, reading, updating, and deleting of data records.

    Explanation

    The video states that the API will have 'full CRUD functionality', which stands for Create, Read, Update, and Delete. This covers all four operations listed in the correct option.

  3. 3

    What is the main challenge of building an API without frameworks like Express.js?

    1. A

      Difficulty in installing and managing project dependencies.

    2. B

      The inability to process JSON data from incoming requests.

    3. C

      Limited access to Node.js built-in HTTP module features.

    4. D

      Manually handling request/response cycles and routing logic.

    Correct answer
    D

    Manually handling request/response cycles and routing logic.

    Explanation

    The tutorial highlights that without a framework like Express, developers must manually figure out 'what route is being hit, what method is being used' and handle the 'http request response cycle' directly, making it harder to write.

  4. 4

    What tool is recommended for making requests to the API during development?

    1. A

      A standard web browser's address bar for all request types.

    2. B

      Node Package Manager (npm) for command-line requests.

    3. C

      Postman, a popular API testing and development environment.

    4. D

      Visual Studio Code's integrated terminal for HTTP calls.

    Correct answer
    C

    Postman, a popular API testing and development environment.

    Explanation

    The instructor explicitly mentions using 'Postman to make requests to my API' and suggests grabbing it from postman.com.

  5. 5

    What type of file is used to store product data in this project?

    1. A

      An XML document storing structured product information.

    2. B

      A SQL database that is accessed via a dedicated client.

    3. C

      A JSON file located in a 'data' folder for simplicity.

    4. D

      A plain text file with comma-separated values for products.

    Correct answer
    C

    A JSON file located in a 'data' folder for simplicity.

    Explanation

    The tutorial states, 'I have a data folder with a products.json file' and that 'we're just going to be dealing with the json file'.

  6. 6

    Which Node.js module is utilized for interacting with the product data file?

    1. A

      The 'fs' (file system) module, which is built into Node.js.

    2. B

      The 'url' module for parsing file uniform resource locators.

    3. C

      The 'http' module for network-based file operations.

    4. D

      The 'path' module for resolving file system directory paths.

    Correct answer
    A

    The 'fs' (file system) module, which is built into Node.js.

    Explanation

    The instructor states, 'we will be using the file system module that node comes with' and later imports it as 'fs'.

  7. 7

    How is the package.json file initially created for this project?

    1. A

      By using a GUI tool to generate the project configuration.

    2. B

      By manually creating the file and populating its content.

    3. C

      By executing node init --yes in the project's folder.

    4. D

      By running npm init -y in the project's root directory.

    Correct answer
    D

    By running npm init -y in the project's root directory.

    Explanation

    The instruction for creating package.json is 'npm init we can add dash y to just skip the questions'.

  8. 8

    What is the sole third-party package installed as a development dependency?

    1. A

      UUID, for generating unique identifiers for product entries.

    2. B

      Express.js, for handling routing and middleware functionalities.

    3. C

      Nodemon, to automatically restart the server on file changes.

    4. D

      Axios, for making HTTP requests to external APIs easily.

    Correct answer
    C

    Nodemon, to automatically restart the server on file changes.

    Explanation

    The instructor states, 'the only third party package that i want to use is nodemon' and explains it 'will just allow us to monitor our server.js files'. Note that UUID is also installed, but is mentioned later as an oversight.

  9. 9

    What are the two npm scripts configured in package.json for this project?

    1. A

      serve for client-side assets and watch for file changes.

    2. B

      deploy for production deployment and debug for development.

    3. C

      build to compile JavaScript files and test for unit testing.

    4. D

      start to run node server.js and dev to run nodemon server.js.

    Correct answer
    D

    start to run node server.js and dev to run nodemon server.js.

    Explanation

    The script configuration is described as 'one is going to be just a standard start script...that's just going to run node and then whatever we call the file which I'm going to call server.js' and 'we're also going to run node mon with the npm run dev command'.

  10. 10

    Which built-in Node.js module is used to create the server?

    1. A

      The http module, which is fundamental for network operations.

    2. B

      The fs module, for managing file system interactions efficiently.

    3. C

      The url module, for parsing and formatting web addresses.

    4. D

      The util module, providing utility functions for developers.

    Correct answer
    A

    The http module, which is fundamental for network operations.

    Explanation

    The server creation process begins with we want to bring in our http module so we want to require http. It's also stated that 'this comes with node.js'.

  11. 11

    What method of the http object is called to initialize the server?

    1. A

      listen(), which specifies the port number for incoming connections.

    2. B

      createServer(), which takes a function with request and response objects.

    3. C

      onConnection(), which handles new client connections to the server.

    4. D

      handleRequest(), which processes the server's incoming HTTP requests.

    Correct answer
    B

    createServer(), which takes a function with request and response objects.

    Explanation

    The instruction states, 'this http object has a method called create server and this this basically kickstarts everything we're able to pass a function in here that takes in a request and response'.

  12. 12

    How is the server configured to listen for incoming requests?

    1. A

      By calling server.listen(portNumber) after creating the server instance.

    2. B

      By passing the port number directly into the http.createServer() method.

    3. C

      By including a <listen> tag within an HTML file served by the server.

    4. D

      By setting an environment variable PORT and the server automatically listens.

    Correct answer
    A

    By calling server.listen(portNumber) after creating the server instance.

    Explanation

    The code structure shown is to 'create a server variable and then down here we'll call server.listen and then it takes in a port number'.

  13. 13

    What is the default port number used if no environment variable PORT is set?

    1. A

      5000, as a common practice for local development servers.

    2. B

      3000, a frequent choice for client-side application development.

    3. C

      80, the standard HTTP port for public web servers.

    4. D

      8080, often used for proxy servers or alternative web services.

    Correct answer
    A

    5000, as a common practice for local development servers.

    Explanation

    The port variable is defined as process.env.PORT or 5000, indicating 5000 is the fallback if the environment variable is not present.

  14. 14

    Why does the initial server implementation 'hang' when a request is made?

    1. A

      Because the server has not yet sent any response back to the client.

    2. B

      Because the requested URL does not match any defined routes.

    3. C

      Because the HTTP module is unable to process incoming requests.

    4. D

      Because the server.listen() method was not properly invoked.

    Correct answer
    A

    Because the server has not yet sent any response back to the client.

    Explanation

    After making an initial request, the instructor states, 'it's going to hang it's not doing anything so i'm going to cancel this and that's because we haven't done anything in this function if i do a console log here of one two three and i send a request it's still gonna hang because i haven't responded with anything'.

  15. 15

    What HTTP status code signifies a successful operation where something was created?

    1. A

      200 (OK), for general successful HTTP requests.

    2. B

      400 (Bad Request), for client-side input errors.

    3. C

      500 (Internal Server Error), for unexpected server issues.

    4. D

      201 (Created), indicating successful resource creation.

    Correct answer
    D

    201 (Created), indicating successful resource creation.

    Explanation

    The explanation of status codes states, '201 means something is created and successful'.

  16. 16

    How is the content type of a response specified in a vanilla Node.js server?

    1. A

      By modifying a global configuration file for content types.

    2. B

      By calling res.setHeader('Content-Type', 'value') on the response object.

    3. C

      By inferring the type based on the data sent in res.write().

    4. D

      By including a <meta> tag in the HTML body of the response.

    Correct answer
    B

    By calling res.setHeader('Content-Type', 'value') on the response object.

    Explanation

    To set the content type, the instruction is 'we want a res dot set Header because the header is where you put stuff like the content type authorization tokens and stuff like that so we can set the header of content-type'.

  17. 17

    What method is used to send the actual body content of an HTTP response?

    1. A

      res.write() followed by res.end() to complete the response.

    2. B

      res.body() for directly populating the response body data.

    3. C

      res.return() to send data and terminate the connection.

    4. D

      res.send() as a simplified method for all response types.

    Correct answer
    A

    res.write() followed by res.end() to complete the response.

    Explanation

    The initial example of sending HTML uses res.write('hello world') and then 'we need to end the response so res dot end'. It later mentions res.end() can also send content directly.

  18. 18

    Why does navigating to /api/products or /abc initially return the same 'Hello World' HTML?

    1. A

      Because the http module automatically defaults to a root path response.

    2. B

      Because the browser caches the initial response and doesn't update it.

    3. C

      Because the server's createServer function lacks URL-specific routing logic.

    4. D

      Because there's an error in setting the Content-Type header value.

    Correct answer
    C

    Because the server's createServer function lacks URL-specific routing logic.

    Explanation

    The instructor explains, 'it's still going to give us that hello world because we we didn't specify any specific url or method or anything like that'.

  19. 19

    How is a JavaScript array of products converted to a JSON string for the response body?

    1. A

      Through a third-party serialization library specifically for JSON.

    2. B

      Node.js automatically handles the conversion when Content-Type is JSON.

    3. C

      Using JSON.stringify(products) before sending it in res.end().

    4. D

      By manually concatenating string parts to form valid JSON output.

    Correct answer
    C

    Using JSON.stringify(products) before sending it in res.end().

    Explanation

    When sending products, the instruction is 'instead of just passing in products by itself we have to wrap it in json.stringify and then pass in products'.

  20. 20

    How does the vanilla Node.js server handle specific URL routes and HTTP methods?

    1. A

      By automatically mapping routes based on file system directory structure.

    2. B

      By using if/else if statements to check request.url and request.method.

    3. C

      By leveraging a built-in routing engine that parses URL patterns.

    4. D

      By employing a separate routing library to define API endpoints.

    Correct answer
    B

    By using if/else if statements to check request.url and request.method.

    Explanation

    To handle routes and methods, the instructor implements 'an if statement and this request object we can get the url' and 'in addition to testing the url let's also say if the request.method...is equal to get'.

  21. 21

    What HTTP status code is used when a requested resource is not found?

    1. A

      404 (Not Found), indicating the server cannot find the requested resource.

    2. B

      500 (Internal Server Error), for server-side processing issues.

    3. C

      302 (Found), for temporary redirection to a different URI.

    4. D

      400 (Bad Request), signifying an invalid request from the client.

    Correct answer
    A

    404 (Not Found), indicating the server cannot find the requested resource.

    Explanation

    In the else block for unmatched routes, the status code is set to '404 not found'.

  22. 22

    What is the purpose of the 'models' folder in the project structure?

    1. A

      To contain functions that interact directly with the data source (JSON file).

    2. B

      To define the data schema and validation rules for product objects.

    3. C

      To render HTML templates and serve static assets to clients.

    4. D

      To hold all the HTTP request and response handling logic for the API.

    Correct answer
    A

    To contain functions that interact directly with the data source (JSON file).

    Explanation

    The explanation for models states, 'models deal with databases or i shouldn't say databases data in this case we're dealing with a json file so it's this is these functions will strictly be used to either get data or create or update or delete data'.

  23. 23

    What is the role of 'controllers' in the project's MVC-like design pattern?

    1. A

      To control route handling, status codes, headers, and interact with models.

    2. B

      To provide the graphical user interface for interacting with the API.

    3. C

      To manage application-wide configuration settings and environment variables.

    4. D

      To directly manipulate the JSON data file without model intervention.

    Correct answer
    A

    To control route handling, status codes, headers, and interact with models.

    Explanation

    Controllers are described as 'going to basically uh you know control whatever that particular route is doing you know the status it's sending what it's sending back any headers we want to send stuff like that and it's also going to interact with the model'.

  24. 24

    Why do model functions return promises in this API design?

    1. A

      To prevent blocking the event loop when performing synchronous file I/O.

    2. B

      To simulate asynchronous data fetching, common in database operations.

    3. C

      To ensure that data is always resolved before being processed by controllers.

    4. D

      To simplify error handling through chained .then() and .catch() calls.

    Correct answer
    B

    To simulate asynchronous data fetching, common in database operations.

    Explanation

    When creating the find function in the model, it's stated, 'usually when you fetch data from either a database or whatever you'll return a promise'.

  25. 25

    How are modules exported in Node.js for use in other files?

    1. A

      By assigning properties or functions to the module.exports object.

    2. B

      By declaring functions as global variables accessible everywhere.

    3. C

      By simply defining functions within the file without explicit export.

    4. D

      By using the export default syntax for ES module compatibility.

    Correct answer
    A

    By assigning properties or functions to the module.exports object.

    Explanation

    The code demonstrates module.exports.find = find; (or directly module.exports = { find };) to make functions available outside the file.

  26. 26

    Why are controller functions made async when interacting with models?

    1. A

      Because async functions automatically handle errors in a try-catch block.

    2. B

      To enable the use of non-blocking I/O operations by default.

    3. C

      Because model functions return promises that need to be awaited.

    4. D

      To allow multiple requests to be processed concurrently by the server.

    Correct answer
    C

    Because model functions return promises that need to be awaited.

    Explanation

    When discussing the getProducts controller function, it's explained 'it's going to be asynchronous because we're going to call our model function which returns a promise'. The await keyword is then used.

  27. 27

    How is a specific product ID extracted from the URL like /api/products/123?

    1. A

      By splitting request.url by / and taking the last element.

    2. B

      By parsing the URL query parameters for an id field.

    3. C

      By using request.params.id as commonly done in Express.js.

    4. D

      By matching a regular expression and extracting the captured group.

    Correct answer
    A

    By splitting request.url by / and taking the last element.

    Explanation

    To get the ID, the method is 'call split which takes a string and splits it into an array and i want to split it by the slash so that way it'll be like this api slash products slash and id it turns it into an array where this is the zero index this is the two this is the three index so i want to get the three that's going to give me the id'.

  28. 28

    What is the typical HTTP method for retrieving data from the server?

    1. A

      PUT, used for updating existing resources on the server.

    2. B

      DELETE, used for removing a specific resource from the server.

    3. C

      POST, used for submitting new data to be processed by the server.

    4. D

      GET, used for requesting data without altering server state.

    Correct answer
    D

    GET, used for requesting data without altering server state.

    Explanation

    When defining the logic for getting products, the instructor states, 'it should only be a get request because get is to do just that get data from the server'.

  29. 29

    Why is the uuid package installed as a dependency?

    1. A

      To provide unique hashes for password encryption.

    2. B

      To create universally unique names for product images.

    3. C

      To generate unique identifiers for new products automatically.

    4. D

      To manage different versions of the API for clients.

    Correct answer
    C

    To generate unique identifiers for new products automatically.

    Explanation

    The instructor states, 'i'm actually going to use a separate uh package...it's just a package called uuid so let's say npm install uuid just to generate an id for us'.

  30. 30

    What is the HTTP status code for a successful resource creation?

    1. A

      204 (No Content), for requests that were successful but return no body.

    2. B

      301 (Moved Permanently), signaling a permanent URI redirection.

    3. C

      200 (OK), indicating a general successful response from the server.

    4. D

      201 (Created), specifically for new resource creation events.

    Correct answer
    D

    201 (Created), specifically for new resource creation events.

    Explanation

    When creating a product, the response is set to res.writeHead(201, ...) with the explanation '201 which means created'.

  31. 31

    How does the create function in the product model add an ID to a new product?

    1. A

      It uses a hash function to create an ID based on product properties.

    2. B

      It uses the uuid package's v4() method to generate a unique ID.

    3. C

      It takes the ID directly from the incoming request body data.

    4. D

      It increments the ID from the last product found in the JSON file.

    Correct answer
    B

    It uses the uuid package's v4() method to generate a unique ID.

    Explanation

    In the create function, newProduct is created with id: uuid.v4(), which 'is going to generate random id or a unique id'.

  32. 32

    What is the purpose of the utils.js file in this project?

    1. A

      To define error handling middleware for various HTTP errors.

    2. B

      To provide utility functions like writing data to a file asynchronously.

    3. C

      To store common constants and configuration variables for the API.

    4. D

      To manage environment-specific settings for different deployments.

    Correct answer
    B

    To provide utility functions like writing data to a file asynchronously.

    Explanation

    A utility function writeDataToFile is created in utils.js to 'write data to a file'. It's used to update the products.json file.

  33. 33

    Which Node.js fs module method is used to write data synchronously to the JSON file?

    1. A

      fs.writeFile(), an asynchronous method that requires a callback function.

    2. B

      fs.writeFileSync(), which blocks until the file operation is complete.

    3. C

      fs.createWriteStream(), for streaming data to a file efficiently.

    4. D

      fs.appendFileSync(), for adding content to the end of a file.

    Correct answer
    B

    fs.writeFileSync(), which blocks until the file operation is complete.

    Explanation

    The writeDataToFile function uses fs.writeFileSync to 'make this easy on ourselves and write this synchronously'.

  34. 34

    How is incoming JSON request body data processed in a vanilla Node.js server?

    1. A

      By reading the Content-Type header and automatically deserializing the body.

    2. B

      By listening for 'data' and 'end' events on the request object and parsing the accumulated chunks.

    3. C

      By using request.body directly after an Express-like body-parser middleware.

    4. D

      By making a separate HTTP request to a local service that processes JSON.

    Correct answer
    B

    By listening for 'data' and 'end' events on the request object and parsing the accumulated chunks.

    Explanation

    The process involves request.on('data', chunk => body += chunk.toString()) and request.on('end', () => JSON.parse(body)). This is later abstracted into getPostData.

  35. 35

    What is the HTTP method used for updating an existing resource on the server?

    1. A

      POST, for creating new resources or submitting data for processing.

    2. B

      GET, for retrieving a representation of the specified resource.

    3. C

      PUT, which typically replaces the entire resource with the new data.

    4. D

      PATCH, used for applying partial modifications to a resource.

    Correct answer
    C

    PUT, which typically replaces the entire resource with the new data.

    Explanation

    When setting up the update route, the condition request.method is equal to put is used, indicating PUT is the method for updates.

  36. 36

    How does the updateProduct controller function handle partial updates?

    1. A

      It requires all fields to be sent in the request body, overwriting old data.

    2. B

      It uses a ternary operator to retain existing data if not provided in the request body.

    3. C

      It merges the incoming data with the existing product using a deep merge utility.

    4. D

      It performs separate database calls for each field that needs updating.

    Correct answer
    B

    It uses a ternary operator to retain existing data if not provided in the request body.

    Explanation

    For updates, fields are set as title: title || product.title, meaning if the new title is not provided, the existing product.title is kept. This allows for partial updates.

  37. 37

    What HTTP status code indicates a successful update operation?

    1. A

      200 (OK), for general success, as content is modified.

    2. B

      201 (Created), which implies a new resource has been added.

    3. C

      202 (Accepted), indicating the request has been accepted for processing.

    4. D

      204 (No Content), if the server successfully processes but sends no body.

    Correct answer
    A

    200 (OK), for general success, as content is modified.

    Explanation

    For updating, the response status is 200 with the explanation '201 is created we're updating'.

  38. 38

    What is the HTTP method used for deleting a resource from the server?

    1. A

      POST, if used with a specific /delete endpoint.

    2. B

      GET, with a query parameter indicating the item to remove.

    3. C

      DELETE, specifically designed for removing resources.

    4. D

      PURGE, an uncommon method for permanent resource removal.

    Correct answer
    C

    DELETE, specifically designed for removing resources.

    Explanation

    The route for deletion is checked with request.method is equal to delete, confirming DELETE is the method.

  39. 39

    How does the remove function in the product model delete a product?

    1. A

      It marks the product as inactive in the array rather than physically deleting it.

    2. B

      It filters the products array to exclude the item with the specified ID and rewrites the file.

    3. C

      It sends a command to a database to execute a DELETE query for the product.

    4. D

      It directly modifies the JSON file to remove the product entry at a given index.

    Correct answer
    B

    It filters the products array to exclude the item with the specified ID and rewrites the file.

    Explanation

    The remove function uses products.filter(p => p.id !== id) to 'filter out whatever one whatever id is passed in here that we want to remove' and then rewrites the file with the filtered array.

Question 1 of 39
Question 1 of 39

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent