Wednesday, 29 January 2025

Lecture Notes Of Class 11: Working with JSON and APIs in Express.js

Lecture Notes Of Class 11: Working with JSON and APIs in Express.js

Objective:

By the end of this class, students will:

  • Understand how to work with JSON data in Express.js.
  • Be able to build simple RESTful APIs to handle JSON data.
  • Know how to test APIs using tools like Postman or curl.
  • Learn to handle different HTTP methods for CRUD operations (Create, Read, Update, and Delete).

1. Introduction to JSON in Express.js

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines. It is often used for exchanging data between a client and a server. In Express.js, we commonly deal with JSON data when building APIs.

Express.js is a web application framework for Node.js that simplifies routing and handling HTTP requests, including those that involve JSON data.

Key Points:

  • JSON format: Data is represented in key-value pairs.
  • Common usage: APIs usually send and receive data in JSON format.

Example of a simple JSON object:

json
{
  "id": 1,
  "name": "John Doe",
  "email": "john.doe@example.com"
}

2. Setting up an Express.js Application

Before we begin building the API, let’s create a basic Express.js app.

Step 1: Install Express.js

1.  If you don't already have Node.js installed, install it from Node.js official website.

2.  Create a new directory for your project:

bash
mkdir express-api
cd express-api

3.  Initialize the project with npm (Node's package manager):

bash
npm init -y

4.  Install Express.js:

bash
npm install express

Step 2: Create a Simple Express Server

In your project directory, create a file named server.js and add the following code to set up the Express server:

javascript
const express = require('express');
const app = express();
const port = 3000;
 
// Middleware to parse JSON bodies
app.use(express.json());
 
// Simple route
app.get('/', (req, res) => {
  res.send('Hello, World!');
});
 
// Start the server
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

In this code:

  • We import Express and create an instance of it with express().
  • The express.json() middleware is used to parse incoming requests with JSON payloads.
  • We set up a basic GET route at the root (/) that sends a simple text response.

To run the server, execute:

bash
node server.js

3. Creating a RESTful API to Handle JSON Data

REST (Representational State Transfer) is an architectural style for building APIs that allow clients to perform CRUD operations using HTTP methods. We will create an API to manage user data, with the ability to create, read, update, and delete users.

Step 1: Define the Data Structure

For this example, we'll use a simple in-memory array to store user data. In a real application, this would be stored in a database.

javascript
let users = [
  { id: 1, name: "John Doe", email: "john.doe@example.com" },
  { id: 2, name: "Jane Smith", email: "jane.smith@example.com" }
];

Step 2: Create CRUD Routes

Now, let’s create the routes for handling the different HTTP methods for CRUD operations.

  • Create (POST): Add a new user.
  • Read (GET): Retrieve all users or a specific user.
  • Update (PUT): Update an existing user.
  • Delete (DELETE): Delete a user.
javascript
// Create a new user
app.post('/users', (req, res) => {
  const { name, email } = req.body;
  const newUser = {
    id: users.length + 1,
    name,
    email
  };
  users.push(newUser);
  res.status(201).json(newUser); // Respond with the created user
});
 
// Get all users
app.get('/users', (req, res) => {
  res.json(users);
});
 
// Get a specific user by ID
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found');
  res.json(user);
});
 
// Update a user
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found');
 
  const { name, email } = req.body;
  user.name = name;
  user.email = email;
  res.json(user);
});
 
// Delete a user
app.delete('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
  if (userIndex === -1) return res.status(404).send('User not found');
 
  const deletedUser = users.splice(userIndex, 1);
  res.json(deletedUser[0]);
});

4. Testing the API using Postman or curl

To test our API, we can use tools like Postman or curl. These tools allow us to send HTTP requests and view the responses from our server.

Testing with Postman:

1.  GET all users:

o    Method: GET

o    URL: http://localhost:3000/users

o    Click Send to see the list of users.

2.  GET a specific user:

o    Method: GET

o    URL: http://localhost:3000/users/1

o    Click Send to see the user with ID 1.

3.  POST a new user:

o    Method: POST

o    URL: http://localhost:3000/users

o    Body: Choose raw and select JSON format.

o    JSON body:

json
{
  "name": "Alice Johnson",
  "email": "alice.johnson@example.com"
}

o    Click Send to add the new user.

4.  PUT update a user:

o    Method: PUT

o    URL: http://localhost:3000/users/1

o    Body: JSON data with updated information.

json
{
  "name": "Johnathan Doe",
  "email": "johnathan.doe@example.com"
}

o    Click Send to update the user.

5.  DELETE a user:

o    Method: DELETE

o    URL: http://localhost:3000/users/1

o    Click Send to delete the user with ID 1.

Testing with curl:

You can also test the API from the command line using curl. Here are examples of the same operations:

·         GET all users:

bash
curl http://localhost:3000/users

·         GET a specific user:

bash
curl http://localhost:3000/users/1

·         POST a new user:

bash
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "Alice Johnson", "email": "alice.johnson@example.com"}'

·         PUT update a user:

bash
curl -X PUT http://localhost:3000/users/1 -H "Content-Type: application/json" -d '{"name": "Johnathan Doe", "email": "johnathan.doe@example.com"}'

·         DELETE a user:

bash
curl -X DELETE http://localhost:3000/users/1

5. Conclusion

In this class, we:

  • Learned about JSON data and how it's used in Express.js applications.
  • Created a simple RESTful API that handles JSON data with CRUD operations (Create, Read, Update, Delete).
  • Tested the API using tools like Postman and curl.

By understanding how to build APIs and handle JSON, you are now equipped with the skills to create dynamic applications that can communicate with external systems.


Lab Tasks Recap:

1.  Create a RESTful API to handle JSON data.

2.  Test the API using Postman or curl.

3.  Handle different HTTP methods for CRUD operations.


This concludes the class.

You said:

Explian in deatil...Lab Tasks Recap: Create a RESTful API to handle JSON data. Test the API using Postman or curl. Handle different HTTP methods for CRUD operations.

ChatGPT said:

ChatGPT

Lab Tasks Recap (Detailed Explanation)

Let’s break down each lab task and explore them in detail to understand the concepts better:


1. Create a RESTful API to Handle JSON Data

What is a RESTful API?

A RESTful API (Representational State Transfer) is a standard architecture for creating web services that allow communication between clients and servers. It relies on HTTP methods and is designed to handle stateless requests, which means each request from a client to a server contains all the information needed for the server to process it. RESTful APIs typically work with JSON (JavaScript Object Notation) to send and receive data.

  • JSON is a text-based format that represents structured data using key-value pairs. It is easy to read and write for both humans and machines.

Building a Simple RESTful API in Express.js

To create a RESTful API in Express.js, we need to set up routes for different HTTP methods (GET, POST, PUT, DELETE) to manage data. Below are the steps to create a simple API that will handle user data in JSON format.

Step 1: Initialize Project and Install Dependencies

1.  Create a directory for the project:

bash
mkdir express-api
cd express-api

2.  Initialize the project:

bash
npm init -y

3.  Install Express.js:

bash
npm install express

4.  Create a file called server.js and set up the Express server as follows:

javascript
const express = require('express');
const app = express();
const port = 3000;
 
// Middleware to parse incoming JSON requests
app.use(express.json());
 
// Sample in-memory data (will act as our database)
let users = [
  { id: 1, name: "John Doe", email: "john.doe@example.com" },
  { id: 2, name: "Jane Smith", email: "jane.smith@example.com" }
];
 
// Start the server
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});
Step 2: Implementing CRUD Operations

We will create routes that correspond to the four main CRUD (Create, Read, Update, Delete) operations:

1.  Create (POST): Add a new user to the data array.

2.  Read (GET): Retrieve a list of all users or a single user by their ID.

3.  Update (PUT): Modify an existing user’s information.

4.  Delete (DELETE): Remove a user from the data array.

Here’s how we’ll set them up:

javascript
// 1. Create a new user (POST request)
app.post('/users', (req, res) => {
  const { name, email } = req.body;
  const newUser = {
    id: users.length + 1,
    name,
    email
  };
  users.push(newUser);
  res.status(201).json(newUser); // Return the created user with status 201 (Created)
});
 
// 2. Get all users (GET request)
app.get('/users', (req, res) => {
  res.json(users); // Return all users in JSON format
});
 
// 3. Get a specific user by ID (GET request)
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found'); // Return 404 if user not found
  res.json(user); // Return the user in JSON format
});
 
// 4. Update a user by ID (PUT request)
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found'); // Return 404 if user not found
 
  const { name, email } = req.body;
  user.name = name;
  user.email = email;
  res.json(user); // Return the updated user
});                                                    
 
// 5. Delete a user by ID (DELETE request)
app.delete('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
  if (userIndex === -1) return res.status(404).send('User not found'); // Return 404 if user not found
 
  const deletedUser = users.splice(userIndex, 1);
  res.json(deletedUser[0]); // Return the deleted user
});

Key Points:

  • POST: Used to create a new resource (user in this case).
  • GET: Used to retrieve resources (list of users or a single user).
  • PUT: Used to update an existing resource.
  • DELETE: Used to remove a resource.

This API allows clients to interact with JSON data (users) using these HTTP methods.


2. Test the API Using Postman or curl

Once the API is created, we need to test it to make sure it is working correctly. We can do this using two common tools: Postman and curl.

Testing with Postman:

Postman is a GUI tool that makes it easy to send HTTP requests and inspect the responses. Here’s how you can test your API with Postman:

1.  Test GET Request (Get all users):

o    Open Postman and select the GET method.

o    In the URL field, enter: http://localhost:3000/users

o    Click Send. You should see a list of users in the response.

2.  Test POST Request (Create a new user):

o    Select the POST method in Postman.

o    In the URL field, enter: http://localhost:3000/users

o    In the Body section, select raw and choose JSON.

o    Add the following JSON data:

json
{
  "name": "Alice Johnson",
  "email": "alice.johnson@example.com"
}

o    Click Send. You should receive a response with the newly created user.

3.  Test PUT Request (Update a user):

o    Select the PUT method in Postman.

o    In the URL field, enter: http://localhost:3000/users/1 (assuming you're updating user with ID 1).

o    In the Body section, add the updated user data:

json
{
  "name": "Johnathan Doe",
  "email": "johnathan.doe@example.com"
}

o    Click Send. You should receive a response with the updated user data.

4.  Test DELETE Request (Delete a user):

o    Select the DELETE method in Postman.

o    In the URL field, enter: http://localhost:3000/users/1

o    Click Send. You should receive a response with the deleted user's data.


Testing with curl:

curl is a command-line tool to send HTTP requests. You can test the API using simple terminal commands.

·         GET all users:

bash
curl http://localhost:3000/users

·         GET a specific user (for example, user with ID 1):

bash
curl http://localhost:3000/users/1

·         POST a new user:

bash
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "Alice Johnson", "email": "alice.johnson@example.com"}'

·         PUT update a user (for example, user with ID 1):

bash
curl -X PUT http://localhost:3000/users/1 -H "Content-Type: application/json" -d '{"name": "Johnathan Doe", "email": "johnathan.doe@example.com"}'

·         DELETE a user (for example, user with ID 1):

bash
curl -X DELETE http://localhost:3000/users/1

3. Handle Different HTTP Methods for CRUD Operations

CRUD stands for Create, Read, Update, and Delete, and these operations are mapped to HTTP methods:

1.  POSTCreate a new resource.

2.  GETRead or fetch an existing resource.

3.  PUTUpdate an existing resource.

4.  DELETEDelete an existing resource.

Each HTTP method is used for different actions:

  • POST creates a new record (user).
  • GET fetches the data, either all records or a specific one.
  • PUT updates an existing record with new information.
  • DELETE removes a record from the system.

In Express.js, we map these methods to appropriate routes in the application. For example:

  • app.post('/users'): Handle POST request to create a new user.
  • app.get('/users'): Handle GET request to retrieve all users.
  • app.put('/users/:id'): Handle PUT request to update a specific user by ID.
  • app.delete('/users/:id'): Handle DELETE request to delete a specific user by ID.

Conclusion

In this lab task, you created a RESTful API that handles JSON data. You then tested the API using Postman and curl. Finally, you learned how to handle different HTTP methods to perform CRUD operations on the data, which forms the core functionality of any API.

You said:

WRITE 10 ASSIGNMENTS FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with proper explanation in details

ChatGPT said:

ChatGPT

Assignments on Working with JSON and APIs in Express.js

Below are 10 assignments related to the concepts of working with JSON and building APIs in Express.js. Each assignment is followed by detailed step-by-step solutions.


Assignment 1: Set Up an Express Server

Objective: Set up a simple Express server and confirm that it works correctly.

Steps:

1.  Create a new directory called express-server.

2.  Run npm init -y to initialize the project.

3.  Install Express.js using npm install express.

4.  Create a server.js file and write the following code to set up a simple Express server:

javascript
const express = require('express');
const app = express();
const port = 3000;
 
app.get('/', (req, res) => {
  res.send('Hello World!');
});
 
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

5.  Run the server using the command node server.js.

6.  Open a browser and visit http://localhost:3000 to ensure the server is running.


Assignment 2: Create a GET Endpoint to Retrieve JSON Data

Objective: Create an API endpoint that returns a list of users in JSON format.

Steps:

1.  Set up the same express-server project.

2.  Create a new route that handles a GET request to /users:

javascript
const users = [
  { id: 1, name: "Alice", email: "alice@example.com" },
  { id: 2, name: "Bob", email: "bob@example.com" }
];
 
app.get('/users', (req, res) => {
  res.json(users); // Send the users array as JSON response
});

3.  Restart the server and navigate to http://localhost:3000/users in your browser to see the list of users in JSON format.


Assignment 3: Create a POST Endpoint to Add a New User

Objective: Create an API endpoint to allow the addition of a new user via a POST request.

Steps:

1.  Set up the same express-server project.

2.  Add a POST endpoint at /users to add a new user:

javascript
app.use(express.json()); // Middleware to parse JSON bodies
 
app.post('/users', (req, res) => {
  const { name, email } = req.body;
  const newUser = { id: users.length + 1, name, email };
  users.push(newUser);
  res.status(201).json(newUser); // Send the created user as a JSON response
});

3.  Test the POST endpoint using Postman:

o    Set the URL to http://localhost:3000/users.

o    Choose POST as the method.

o    In the body, add JSON data:

json
{
  "name": "Charlie",
  "email": "charlie@example.com"
}

4.  Verify that the new user is added and a response with the new user is returned.


Assignment 4: Create a PUT Endpoint to Update an Existing User

Objective: Implement an API endpoint to update an existing user's data.

Steps:

1.  Set up the same express-server project.

2.  Add a PUT endpoint to update user information by ID:

javascript
app.put('/users/:id', (req, res) => {
  const { id } = req.params;
  const { name, email } = req.body;
 
  const user = users.find(u => u.id === parseInt(id));
  if (!user) return res.status(404).send('User not found');
  
  user.name = name;
  user.email = email;
 
  res.json(user); // Send the updated user as a JSON response
});

3.  Test the PUT endpoint using Postman:

o    Set the URL to http://localhost:3000/users/1.

o    Choose PUT as the method.

o    In the body, update the user details:

json
{
  "name": "Updated Name",
  "email": "updated.email@example.com"
}

4.  Verify that the user with ID 1 is updated with the new data.


Assignment 5: Create a DELETE Endpoint to Remove a User

Objective: Implement an API endpoint to delete a user by ID.

Steps:

1.  Set up the same express-server project.

2.  Add a DELETE endpoint to delete a user by their ID:

javascript
app.delete('/users/:id', (req, res) => {
  const { id } = req.params;
  const userIndex = users.findIndex(u => u.id === parseInt(id));
  
  if (userIndex === -1) return res.status(404).send('User not found');
  
  const deletedUser = users.splice(userIndex, 1);
  res.json(deletedUser[0]); // Return the deleted user data
});

3.  Test the DELETE endpoint using Postman:

o    Set the URL to http://localhost:3000/users/1.

o    Choose DELETE as the method.

4.  Verify that the user with ID 1 is deleted from the list.


Assignment 6: Return 404 Error for Non-Existent User

Objective: Implement a check to handle cases when a user does not exist.

Steps:

1.  Set up the same express-server project.

2.  Modify the GET user endpoint to handle non-existent users:

javascript
app.get('/users/:id', (req, res) => {
  const { id } = req.params;
  const user = users.find(u => u.id === parseInt(id));
 
  if (!user) return res.status(404).json({ message: 'User not found' });
  
  res.json(user); // Return the user data
});

3.  Test the endpoint by trying to access a non-existent user ID like http://localhost:3000/users/100.


Assignment 7: Implement Query Parameters for Filtering Users

Objective: Allow filtering users based on query parameters (e.g., name).

Steps:

1.  Set up the same express-server project.

2.  Modify the GET /users endpoint to accept a query parameter for filtering by name:

javascript
app.get('/users', (req, res) => {
  const { name } = req.query;
  const filteredUsers = name
    ? users.filter(u => u.name.toLowerCase().includes(name.toLowerCase()))
    : users;
  res.json(filteredUsers); // Return the filtered list of users
});

3.  Test the endpoint using a query string like http://localhost:3000/users?name=Alice to return users whose name contains "Alice".


Assignment 8: Handle Invalid JSON Input with Error Handling

Objective: Add error handling for invalid JSON input in the POST and PUT requests.

Steps:

1.  Set up the same express-server project.

2.  Modify the POST and PUT routes to handle invalid JSON input:

javascript
app.post('/users', (req, res) => {
  if (!req.body.name || !req.body.email) {
    return res.status(400).send('Name and email are required');
  }
 
  const newUser = { id: users.length + 1, name: req.body.name, email: req.body.email };
  users.push(newUser);
  res.status(201).json(newUser); // Return the created user
});
 
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found');
 
  if (!req.body.name || !req.body.email) {
    return res.status(400).send('Name and email are required');
  }
 
  user.name = req.body.name;
  user.email = req.body.email;
 
  res.json(user); // Return the updated user
});

3.  Test the error handling by sending incomplete or incorrect JSON data in the POST or PUT requests.


Assignment 9: Use Middleware to Log Request Details

Objective: Implement middleware to log request details before reaching the route handler.

Steps:

1.  Set up the same express-server project.

2.  Add a middleware function to log the HTTP method and URL for each request:

javascript
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Pass control to the next middleware or route handler
});

3.  Test the server by sending requests, and check the console for logs of each request's details.


Assignment 10: Use a JSON File as Data Storage

Objective: Replace the in-memory users array with a JSON file as data storage.

Steps:

1.  Create a file called data.json with the following contents:

json
[
  { "id": 1, "name": "Alice", "email": "alice@example.com" },
  { "id": 2, "name": "Bob", "email": "bob@example.com" }
]

2.  In the server.js file, replace the users array with the data from data.json:

javascript
const fs = require('fs');
const path = './data.json';
 
const readData = () => {
  const data = fs.readFileSync(path, 'utf-8');
  return JSON.parse(data);
};
 
const writeData = (data) => {
  fs.writeFileSync(path, JSON.stringify(data, null, 2));
};
 
app.get('/users', (req, res) => {
  const users = readData();
  res.json(users);
});
 
app.post('/users', (req, res) => {
  const users = readData();
  const { name, email } = req.body;
  const newUser = { id: users.length + 1, name, email };
  users.push(newUser);
  writeData(users);
  res.status(201).json(newUser);
});

3.  Verify that user data is now read from and written to data.json instead of being stored in memory.


These assignments should give students hands-on practice in building and interacting with APIs using Express.js while learning to handle JSON data effectively.

You said:

WRITE 50 no of MCQs only FROM ABOVE CONCEPT with explanation

ChatGPT said:

ChatGPT

Here are 50 multiple-choice questions (MCQs) based on the concepts of working with JSON and **APIs in Express.js, along with explanations for each answer:


1. What does JSON stand for?

a) JavaScript Online Notation
b) JavaScript Object Notation
c) Java Object Notation
d) Java Standard Object Notation

Answer: b) JavaScript Object Notation
Explanation: JSON is a lightweight data interchange format based on JavaScript object syntax.


2. Which HTTP method is used to retrieve data from the server?

a) POST
b) PUT
c) GET
d) DELETE

Answer: c) GET
Explanation: The GET method is used to request data from a specified resource.


3. Which method in Express.js is used to define a route that handles GET requests?

a) app.post()
b) app.put()
c) app.get()
d) app.delete()

Answer: c) app.get()
Explanation: The app.get() method is used to define a route that handles GET requests in Express.js.


4. What does res.json() do in an Express.js route handler?

a) It sends a JSON object as the response
b) It parses incoming JSON data
c) It sends an HTML page as the response
d) It logs the data to the console

Answer: a) It sends a JSON object as the response
Explanation: The res.json() method sends a JSON response to the client.


5. How can you parse JSON data in the body of a POST request in Express.js?

a) app.use(express.json())
b) app.use(bodyParser.json())
c) app.parseJSON()
d) app.bodyParser()

Answer: a) app.use(express.json())
Explanation: To parse JSON data in POST request bodies, we need to use the middleware express.json().


6. Which HTTP method is used to update existing data on the server?

a) POST
b) GET
c) PUT
d) DELETE

Answer: c) PUT
Explanation: The PUT method is used to update existing resources on the server.


7. How can you add new data in an Express API using HTTP methods?

a) PUT
b) POST
c) GET
d) DELETE

Answer: b) POST
Explanation: The POST method is used to create new resources on the server.


8. Which of the following status codes indicates a successful HTTP request?

a) 500
b) 404
c) 200
d) 301

Answer: c) 200
Explanation: 200 is the HTTP status code indicating that the request was successful.


9. Which method is used in Express.js to handle DELETE requests?

a) app.put()
b) app.get()
c) app.post()
d) app.delete()

Answer: d) app.delete()
Explanation: The app.delete() method is used to handle DELETE requests in Express.js.


10. What does the following Express code do?

javascript
app.get('/users', (req, res) => {
  res.json(users);
});

a) It fetches and displays user data in an HTML page
b) It sends the JSON data for users as the response
c) It stores users data in the database
d) It deletes user data

Answer: b) It sends the JSON data for users as the response
Explanation: This code sends the list of users in JSON format as a response to a GET request.


11. How do you extract data from the body of a POST request in Express.js?

a) req.body()
b) req.query()
c) req.body
d) req.params

Answer: c) req.body
Explanation: req.body contains the data sent in the body of a POST request after parsing by middleware like express.json().


12. What does the req.params object in Express contain?

a) Query string parameters
b) Request headers
c) URL parameters
d) Request body

Answer: c) URL parameters
Explanation: The req.params object contains route parameters, which are part of the URL path.


13. What is the default port number for an Express.js server?

a) 3000
b) 8080
c) 5000
d) 4000

Answer: a) 3000
Explanation: By default, Express.js applications listen on port 3000 unless specified otherwise.


14. What type of HTTP request does a client send to delete data from a server?

a) PUT
b) DELETE
c) GET
d) POST

Answer: b) DELETE
Explanation: The DELETE method is used to remove data from the server.


15. What would be the status code for a failed POST request due to missing required data?

a) 404
b) 500
c) 400
d) 200

Answer: c) 400
Explanation: A 400 status code indicates that the server could not process the request due to a client error, such as missing data.


16. Which method is used to include middleware in Express.js?

a) app.use()
b) app.apply()
c) app.include()
d) app.middleware()

Answer: a) app.use()
Explanation: app.use() is used to include middleware functions in Express.js.


17. Which of the following is a correct way to send JSON data in a POST request using Postman?

a) Send data as plain text
b) Use the raw option and select JSON in the body
c) Use URL parameters to send data
d) Include JSON in the header

Answer: b) Use the raw option and select JSON in the body
Explanation: In Postman, the raw option allows you to send data in various formats, including JSON.


18. Which of the following Express.js functions allows you to handle a POST request?

a) app.get()
b) app.post()
c) app.put()
d) app.delete()

Answer: b) app.post()
Explanation: app.post() is used to handle POST requests in Express.js.


19. How can you return a JSON response with a custom status code in Express.js?

a) res.sendStatus()
b) res.json()
c) res.send()
d) res.status().json()

Answer: d) res.status().json()
Explanation: res.status().json() allows you to send a JSON response with a custom status code.


20. What is the purpose of middleware in Express.js?

a) To handle database queries
b) To manage client-side data
c) To process requests before they reach route handlers
d) To perform background tasks

Answer: c) To process requests before they reach route handlers
Explanation: Middleware functions are used to modify the request or response objects before they are passed to the route handlers.


21. Which of the following would be a correct endpoint for deleting a user with ID 1 in Express.js?

a) DELETE /users/1
b) DELETE /users?id=1
c) POST /users/1/delete
d) DELETE /deleteUser/1

Answer: a) DELETE /users/1
Explanation: RESTful URLs typically include the resource identifier in the path, such as /users/1 for a DELETE request.


22. What is the purpose of express.json() middleware in Express?

a) It encodes data in JSON format
b) It decodes JSON data in the request body
c) It checks for syntax errors in JSON
d) It logs the request headers

Answer: b) It decodes JSON data in the request body
Explanation: express.json() is middleware used to parse incoming JSON data in the request body.


23. What will be the response status code for a successful POST request?

a) 404
b) 500
c) 201
d) 301

Answer: c) 201
Explanation: 201 indicates that a resource was successfully created in response to a POST request.


24. What will happen if you try to call res.json() with invalid data?

a) It will send an error response automatically
b) The server will crash
c) It will send a 500 internal server error
d) It will ignore the request

Answer: a) It will send an error response automatically
Explanation: If the data provided to res.json() is invalid, Express will automatically handle it and respond with a 500 Internal Server Error.


25. How can you ensure a JSON response is pretty-printed?

a) Pass the pretty option to res.json()
b) Use the JSON.stringify() method with the space argument
c) Pretty-print is automatic in Express.js
d) Set the Accept header to application/json

Answer: b) Use the JSON.stringify() method with the space argument
Explanation: The space argument in JSON.stringify() ensures that the output is formatted with indentation for better readability.


26. Which HTTP method is used to replace a resource on the server?

a) POST
b) PUT
c) GET
d) DELETE

Answer: b) PUT
Explanation: The PUT method is used to update or replace an existing resource.


27. In which format does Express.js send JSON responses by default?

a) XML
b) HTML
c) JSON
d) Text

Answer: c) JSON
Explanation: By default, Express.js sends responses in JSON format when using res.json().


28. How do you handle errors in Express.js route handlers?

a) app.error()
b) next()
c) res.error()
d) app.catch()

Answer: b) next()
Explanation: Errors are passed to the error-handling middleware using the next() function in Express.js.


29. Which of the following is the correct syntax to define a route handler for PUT requests in Express.js?

a) app.put('/route', handler)
b) app.get('/route', handler)
c) app.post('/route', handler)
d) app.delete('/route', handler)

Answer: a) app.put('/route', handler)
Explanation: The app.put() method is used to define a handler for PUT requests.


30. What is the best way to send a response with a 404 status code in Express?

a) res.send(404)
b) res.status(404).send("Not Found")
c) res.sendStatus(404)
d) res.status("404")

Answer: b) res.status(404).send("Not Found")
Explanation: The res.status(404) method sets the status code to 404, and res.send() sends the response body.


31. Which HTTP method is commonly used to fetch data without causing side effects?

a) POST
b) GET
c) PUT
d) DELETE

Answer: b) GET
Explanation: The GET method is used to retrieve data without causing side effects on the server.


32. Which function is used to handle errors in Express.js?

a) app.error()
b) app.catch()
c) next()
d) res.error()

Answer: c) next()
Explanation: The next() function is used to pass control to the next middleware or error handler.


33. How do you validate incoming JSON data in an Express route?

a) By using middleware like express-validator
b) By manually checking req.body
c) Express does not allow validation
d) By setting headers to validate the data

Answer: a) By using middleware like express-validator
Explanation: Middleware like express-validator can be used to validate incoming data.


34. What would happen if a POST request did not include the correct content type header?

a) The server will send a 404 response
b) The server will automatically parse the body
c) The server may not parse the request body correctly
d) The request will fail silently

Answer: c) The server may not parse the request body correctly
Explanation: If the content type is incorrect, Express may not be able to parse the request body as expected.


35. Which of the following is the correct way to make a request to an API using curl?

a) curl -X GET /api/endpoint
b) curl -GET /api/endpoint
c) curl --method GET /api/endpoint
d) curl GET /api/endpoint

Answer: a) curl -X GET /api/endpoint
Explanation: The curl -X option specifies the HTTP method to use.


36. What is the purpose of res.status(201) in Express.js?

a) To indicate successful request processing
b) To send a generic error message
c) To indicate a resource has been successfully created
d) To redirect the user to another page

Answer: c) To indicate a resource has been successfully created
Explanation: 201 indicates that the request has been fulfilled and a new resource has been created.


37. How do you enable JSON responses in Postman?

a) Set the header to application/json
b) Use the raw option and select JSON from the dropdown
c) Send JSON as URL parameters
d) Use the POST method for all requests

Answer: b) Use the raw option and select JSON from the dropdown
Explanation: Postman allows you to select JSON under the raw tab to send JSON data.


38. What does the app.use() function do in Express.js?

a) It registers middleware in the Express application
b) It registers routes for the application
c) It starts the server
d) It serves static files

Answer: a) It registers middleware in the Express application
Explanation: app.use() is used to register middleware functions that process requests.


39. Which HTTP status code should be returned for a successful DELETE request?

a) 200
b) 400
c) 404
d) 204

Answer: d) 204
Explanation: 204 indicates that the resource was successfully deleted, and there is no content in the response.


40. Which of the following is the correct way to handle multiple HTTP methods on the same route in Express.js?

a) Use app.all()
b) Define separate handlers for each method
c) Use app.any()
d) Express only supports one method per route

Answer: b) Define separate handlers for each method
Explanation: In Express, each HTTP method (GET, POST, PUT, DELETE) is handled by separate functions like app.get(), app.post(), etc.


41. What is the purpose of req.query in Express.js?

a) It contains the body of the request
b) It contains URL parameters
c) It contains query string parameters
d) It contains cookies

Answer: c) It contains query string parameters
Explanation: req.query contains key-value pairs from the query string in the URL.


42. Which of the following statements is true about RESTful APIs?

a) RESTful APIs use XML exclusively
b) RESTful APIs use HTTP methods to perform CRUD operations
c) RESTful APIs require JSON to work
d) RESTful APIs can only be used with POST and GET

Answer: b) RESTful APIs use HTTP methods to perform CRUD operations
Explanation: RESTful APIs use HTTP methods like GET, POST, PUT, and DELETE to perform CRUD operations.


43. What happens if you don't include express.json() in the middleware for POST requests?

a) The server will crash
b) The body of the request will not be parsed as JSON
c) The server will reject the request
d) Express automatically parses all data

Answer: b) The body of the request will not be parsed as JSON
Explanation: Without express.json(), the server cannot parse the JSON body of a POST request.


44. Which HTTP method is typically used for fetching data from an API?

a) PUT
b) GET
c) DELETE
d) POST

Answer: b) GET
Explanation: GET is the standard HTTP method for fetching data from a server.


45. What is the purpose of app.listen() in Express.js?

a) It starts the server and listens on a port
b) It handles HTTP requests
c) It defines the routes
d) It processes incoming data

Answer: a) It starts the server and listens on a port
Explanation: app.listen() is used to start the Express server on a specified port.


46. Which of the following would you use to modify the response before sending it to the client?

a) req.body
b) req.query
c) res.send()
d) res.status()

Answer: c) res.send()
Explanation: res.send() is used to send the response to the client, and can be modified as needed.


47. Which method is used to handle PUT requests in Express.js?

a) app.put()
b) app.get()
c) app.post()
d) app.delete()

Answer: a) app.put()
Explanation: app.put() is used to define a route that handles PUT requests.


48. How would you send an error response with a 404 status code in Express?

a) res.status(404).send("Not Found")
b) res.send(404)
c) res.status(404).json()
d) res.sendStatus(404)

Answer: a) res.status(404).send("Not Found")
Explanation: This code sends a 404 status code and a message to the client indicating the resource was not found.


49. How do you serve static files in Express.js?

a) app.use(express.static('public'))
b) app.serve('public')
c) app.static('public')
d) app.use(public())

Answer: a) app.use(express.static('public'))
Explanation: express.static() serves static files such as images, CSS, and JavaScript files.


50. What is the default port number for an Express.js application if not specified?

a) 8080
b) 3000
c) 5000
d) 80

Answer: b) 3000

Explanation: If no port is specified, Express.js uses port 3000 by default for the application. 

Search This Blog

Powered by Blogger.

Lecture Notes Of Class 11: Working with JSON and APIs in Express.js

Lecture Notes Of Class 11: Working with JSON and APIs in Express.js Objective: By the end of this class, students will: Understand ...