Node.js REST API
- 39Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is the primary purpose of this Node.js REST API tutorial?
What is the primary purpose of this Node.js REST API tutorial?
39 questions
- 1
What is the primary purpose of this Node.js REST API tutorial?
- A
To build a full CRUD API using only the HTTP module without frameworks.
- B
To explain how to integrate a database with a Node.js API project.
- C
To teach basic Node.js syntax for front-end web development tasks.
- D
To demonstrate the advantages of using Express.js for API development.
Correct answer
ATo 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.
- A
- 2
Which of the following functionalities will the created API support?
- A
Creation, reading, updating, and deleting of data records.
- B
Server-side rendering of dynamic web pages for clients.
- C
Integration with a NoSQL database like MongoDB for storage.
- D
Real-time bidirectional communication using WebSockets.
Correct answer
ACreation, 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.
- A
- 3
What is the main challenge of building an API without frameworks like Express.js?
- A
Difficulty in installing and managing project dependencies.
- B
The inability to process JSON data from incoming requests.
- C
Limited access to Node.js built-in HTTP module features.
- D
Manually handling request/response cycles and routing logic.
Correct answer
DManually 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.
- A
- 4
What tool is recommended for making requests to the API during development?
- A
A standard web browser's address bar for all request types.
- B
Node Package Manager (npm) for command-line requests.
- C
Postman, a popular API testing and development environment.
- D
Visual Studio Code's integrated terminal for HTTP calls.
Correct answer
CPostman, 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.
- A
- 5
What type of file is used to store product data in this project?
- A
An XML document storing structured product information.
- B
A SQL database that is accessed via a dedicated client.
- C
A JSON file located in a 'data' folder for simplicity.
- D
A plain text file with comma-separated values for products.
Correct answer
CA 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'.
- A
- 6
Which Node.js module is utilized for interacting with the product data file?
- A
The 'fs' (file system) module, which is built into Node.js.
- B
The 'url' module for parsing file uniform resource locators.
- C
The 'http' module for network-based file operations.
- D
The 'path' module for resolving file system directory paths.
Correct answer
AThe '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'.
- A
- 7
How is the
package.jsonfile initially created for this project?- A
By using a GUI tool to generate the project configuration.
- B
By manually creating the file and populating its content.
- C
By executing
node init --yesin the project's folder. - D
By running
npm init -yin the project's root directory.
Correct answer
DBy running
npm init -yin the project's root directory.Explanation
The instruction for creating
package.jsonis 'npm init we can add dash y to just skip the questions'. - A
- 8
What is the sole third-party package installed as a development dependency?
- A
UUID, for generating unique identifiers for product entries.
- B
Express.js, for handling routing and middleware functionalities.
- C
Nodemon, to automatically restart the server on file changes.
- D
Axios, for making HTTP requests to external APIs easily.
Correct answer
CNodemon, 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.
- A
- 9
What are the two npm scripts configured in
package.jsonfor this project?- A
servefor client-side assets andwatchfor file changes. - B
deployfor production deployment anddebugfor development. - C
buildto compile JavaScript files andtestfor unit testing. - D
startto runnode server.jsanddevto runnodemon server.js.
Correct answer
Dstartto runnode server.jsanddevto runnodemon 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'.
- A
- 10
Which built-in Node.js module is used to create the server?
- A
The
httpmodule, which is fundamental for network operations. - B
The
fsmodule, for managing file system interactions efficiently. - C
The
urlmodule, for parsing and formatting web addresses. - D
The
utilmodule, providing utility functions for developers.
Correct answer
AThe
httpmodule, 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'. - A
- 11
What method of the
httpobject is called to initialize the server?- A
listen(), which specifies the port number for incoming connections. - B
createServer(), which takes a function with request and response objects. - C
onConnection(), which handles new client connections to the server. - D
handleRequest(), which processes the server's incoming HTTP requests.
Correct answer
BcreateServer(), 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'.
- A
- 12
How is the server configured to listen for incoming requests?
- A
By calling
server.listen(portNumber)after creating the server instance. - B
By passing the port number directly into the
http.createServer()method. - C
By including a
<listen>tag within an HTML file served by the server. - D
By setting an environment variable
PORTand the server automatically listens.
Correct answer
ABy 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'.
- A
- 13
What is the default port number used if no environment variable
PORTis set?- A
5000, as a common practice for local development servers.
- B
3000, a frequent choice for client-side application development.
- C
80, the standard HTTP port for public web servers.
- D
8080, often used for proxy servers or alternative web services.
Correct answer
A5000, 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. - A
- 14
Why does the initial server implementation 'hang' when a request is made?
- A
Because the server has not yet sent any response back to the client.
- B
Because the requested URL does not match any defined routes.
- C
Because the HTTP module is unable to process incoming requests.
- D
Because the
server.listen()method was not properly invoked.
Correct answer
ABecause 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'.
- A
- 15
What HTTP status code signifies a successful operation where something was created?
- A
200 (OK), for general successful HTTP requests.
- B
400 (Bad Request), for client-side input errors.
- C
500 (Internal Server Error), for unexpected server issues.
- D
201 (Created), indicating successful resource creation.
Correct answer
D201 (Created), indicating successful resource creation.
Explanation
The explanation of status codes states, '201 means something is created and successful'.
- A
- 16
How is the content type of a response specified in a vanilla Node.js server?
- A
By modifying a global configuration file for content types.
- B
By calling
res.setHeader('Content-Type', 'value')on the response object. - C
By inferring the type based on the data sent in
res.write(). - D
By including a
<meta>tag in the HTML body of the response.
Correct answer
BBy 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'.
- A
- 17
What method is used to send the actual body content of an HTTP response?
- A
res.write()followed byres.end()to complete the response. - B
res.body()for directly populating the response body data. - C
res.return()to send data and terminate the connection. - D
res.send()as a simplified method for all response types.
Correct answer
Ares.write()followed byres.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 mentionsres.end()can also send content directly. - A
- 18
Why does navigating to
/api/productsor/abcinitially return the same 'Hello World' HTML?- A
Because the
httpmodule automatically defaults to a root path response. - B
Because the browser caches the initial response and doesn't update it.
- C
Because the server's
createServerfunction lacks URL-specific routing logic. - D
Because there's an error in setting the
Content-Typeheader value.
Correct answer
CBecause the server's
createServerfunction 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'.
- A
- 19
How is a JavaScript array of products converted to a JSON string for the response body?
- A
Through a third-party serialization library specifically for JSON.
- B
Node.js automatically handles the conversion when
Content-Typeis JSON. - C
Using
JSON.stringify(products)before sending it inres.end(). - D
By manually concatenating string parts to form valid JSON output.
Correct answer
CUsing
JSON.stringify(products)before sending it inres.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'.
- A
- 20
How does the vanilla Node.js server handle specific URL routes and HTTP methods?
- A
By automatically mapping routes based on file system directory structure.
- B
By using
if/else ifstatements to checkrequest.urlandrequest.method. - C
By leveraging a built-in routing engine that parses URL patterns.
- D
By employing a separate routing library to define API endpoints.
Correct answer
BBy using
if/else ifstatements to checkrequest.urlandrequest.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'.
- A
- 21
What HTTP status code is used when a requested resource is not found?
- A
404 (Not Found), indicating the server cannot find the requested resource.
- B
500 (Internal Server Error), for server-side processing issues.
- C
302 (Found), for temporary redirection to a different URI.
- D
400 (Bad Request), signifying an invalid request from the client.
Correct answer
A404 (Not Found), indicating the server cannot find the requested resource.
Explanation
In the
elseblock for unmatched routes, the status code is set to '404 not found'. - A
- 22
What is the purpose of the 'models' folder in the project structure?
- A
To contain functions that interact directly with the data source (JSON file).
- B
To define the data schema and validation rules for product objects.
- C
To render HTML templates and serve static assets to clients.
- D
To hold all the HTTP request and response handling logic for the API.
Correct answer
ATo 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'.
- A
- 23
What is the role of 'controllers' in the project's MVC-like design pattern?
- A
To control route handling, status codes, headers, and interact with models.
- B
To provide the graphical user interface for interacting with the API.
- C
To manage application-wide configuration settings and environment variables.
- D
To directly manipulate the JSON data file without model intervention.
Correct answer
ATo 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'.
- A
- 24
Why do model functions return promises in this API design?
- A
To prevent blocking the event loop when performing synchronous file I/O.
- B
To simulate asynchronous data fetching, common in database operations.
- C
To ensure that data is always resolved before being processed by controllers.
- D
To simplify error handling through chained
.then()and.catch()calls.
Correct answer
BTo simulate asynchronous data fetching, common in database operations.
Explanation
When creating the
findfunction in the model, it's stated, 'usually when you fetch data from either a database or whatever you'll return a promise'. - A
- 25
How are modules exported in Node.js for use in other files?
- A
By assigning properties or functions to the
module.exportsobject. - B
By declaring functions as global variables accessible everywhere.
- C
By simply defining functions within the file without explicit export.
- D
By using the
export defaultsyntax for ES module compatibility.
Correct answer
ABy assigning properties or functions to the
module.exportsobject.Explanation
The code demonstrates
module.exports.find = find;(or directlymodule.exports = { find };) to make functions available outside the file. - A
- 26
Why are controller functions made
asyncwhen interacting with models?- A
Because
asyncfunctions automatically handle errors in a try-catch block. - B
To enable the use of non-blocking I/O operations by default.
- C
Because model functions return promises that need to be awaited.
- D
To allow multiple requests to be processed concurrently by the server.
Correct answer
CBecause model functions return promises that need to be awaited.
Explanation
When discussing the
getProductscontroller function, it's explained 'it's going to be asynchronous because we're going to call our model function which returns a promise'. Theawaitkeyword is then used. - A
- 27
How is a specific product ID extracted from the URL like
/api/products/123?- A
By splitting
request.urlby/and taking the last element. - B
By parsing the URL query parameters for an
idfield. - C
By using
request.params.idas commonly done in Express.js. - D
By matching a regular expression and extracting the captured group.
Correct answer
ABy splitting
request.urlby/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'.
- A
- 28
What is the typical HTTP method for retrieving data from the server?
- A
PUT, used for updating existing resources on the server.
- B
DELETE, used for removing a specific resource from the server.
- C
POST, used for submitting new data to be processed by the server.
- D
GET, used for requesting data without altering server state.
Correct answer
DGET, 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'.
- A
- 29
Why is the
uuidpackage installed as a dependency?- A
To provide unique hashes for password encryption.
- B
To create universally unique names for product images.
- C
To generate unique identifiers for new products automatically.
- D
To manage different versions of the API for clients.
Correct answer
CTo 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'.
- A
- 30
What is the HTTP status code for a successful resource creation?
- A
204 (No Content), for requests that were successful but return no body.
- B
301 (Moved Permanently), signaling a permanent URI redirection.
- C
200 (OK), indicating a general successful response from the server.
- D
201 (Created), specifically for new resource creation events.
Correct answer
D201 (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'. - A
- 31
How does the
createfunction in the product model add an ID to a new product?- A
It uses a hash function to create an ID based on product properties.
- B
It uses the
uuidpackage'sv4()method to generate a unique ID. - C
It takes the ID directly from the incoming request body data.
- D
It increments the ID from the last product found in the JSON file.
Correct answer
BIt uses the
uuidpackage'sv4()method to generate a unique ID.Explanation
In the
createfunction,newProductis created withid: uuid.v4(), which 'is going to generate random id or a unique id'. - A
- 32
What is the purpose of the
utils.jsfile in this project?- A
To define error handling middleware for various HTTP errors.
- B
To provide utility functions like writing data to a file asynchronously.
- C
To store common constants and configuration variables for the API.
- D
To manage environment-specific settings for different deployments.
Correct answer
BTo provide utility functions like writing data to a file asynchronously.
Explanation
A utility function
writeDataToFileis created inutils.jsto 'write data to a file'. It's used to update theproducts.jsonfile. - A
- 33
Which Node.js
fsmodule method is used to write data synchronously to the JSON file?- A
fs.writeFile(), an asynchronous method that requires a callback function. - B
fs.writeFileSync(), which blocks until the file operation is complete. - C
fs.createWriteStream(), for streaming data to a file efficiently. - D
fs.appendFileSync(), for adding content to the end of a file.
Correct answer
Bfs.writeFileSync(), which blocks until the file operation is complete.Explanation
The
writeDataToFilefunction usesfs.writeFileSyncto 'make this easy on ourselves and write this synchronously'. - A
- 34
How is incoming JSON request body data processed in a vanilla Node.js server?
- A
By reading the
Content-Typeheader and automatically deserializing the body. - B
By listening for 'data' and 'end' events on the
requestobject and parsing the accumulated chunks. - C
By using
request.bodydirectly after an Express-like body-parser middleware. - D
By making a separate HTTP request to a local service that processes JSON.
Correct answer
BBy listening for 'data' and 'end' events on the
requestobject and parsing the accumulated chunks.Explanation
The process involves
request.on('data', chunk => body += chunk.toString())andrequest.on('end', () => JSON.parse(body)). This is later abstracted intogetPostData. - A
- 35
What is the HTTP method used for updating an existing resource on the server?
- A
POST, for creating new resources or submitting data for processing.
- B
GET, for retrieving a representation of the specified resource.
- C
PUT, which typically replaces the entire resource with the new data.
- D
PATCH, used for applying partial modifications to a resource.
Correct answer
CPUT, which typically replaces the entire resource with the new data.
Explanation
When setting up the update route, the condition
request.method is equal to putis used, indicating PUT is the method for updates. - A
- 36
How does the
updateProductcontroller function handle partial updates?- A
It requires all fields to be sent in the request body, overwriting old data.
- B
It uses a ternary operator to retain existing data if not provided in the request body.
- C
It merges the incoming data with the existing product using a deep merge utility.
- D
It performs separate database calls for each field that needs updating.
Correct answer
BIt 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 newtitleis not provided, the existingproduct.titleis kept. This allows for partial updates. - A
- 37
What HTTP status code indicates a successful update operation?
- A
200 (OK), for general success, as content is modified.
- B
201 (Created), which implies a new resource has been added.
- C
202 (Accepted), indicating the request has been accepted for processing.
- D
204 (No Content), if the server successfully processes but sends no body.
Correct answer
A200 (OK), for general success, as content is modified.
Explanation
For updating, the response status is
200with the explanation '201 is created we're updating'. - A
- 38
What is the HTTP method used for deleting a resource from the server?
- A
POST, if used with a specific
/deleteendpoint. - B
GET, with a query parameter indicating the item to remove.
- C
DELETE, specifically designed for removing resources.
- D
PURGE, an uncommon method for permanent resource removal.
Correct answer
CDELETE, specifically designed for removing resources.
Explanation
The route for deletion is checked with
request.method is equal to delete, confirming DELETE is the method. - A
- 39
How does the
removefunction in the product model delete a product?- A
It marks the product as inactive in the array rather than physically deleting it.
- B
It filters the products array to exclude the item with the specified ID and rewrites the file.
- C
It sends a command to a database to execute a DELETE query for the product.
- D
It directly modifies the JSON file to remove the product entry at a given index.
Correct answer
BIt filters the products array to exclude the item with the specified ID and rewrites the file.
Explanation
The
removefunction usesproducts.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. - A

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