Wednesday, 29 January 2025

Lecture Notes Of Class 26: Building a RESTful API (Class 26)

Lecture Notes Of Class 26: Building a RESTful API (Class 26)

Objective:

Learn to build a full RESTful API with Node.js and Express.js, implementing CRUD (Create, Read, Update, Delete) operations for managing resources.


1. Introduction to RESTful API

What is an API?

An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other.

What is a RESTful API?

REST (Representational State Transfer) is an architectural style for building web services that use HTTP methods to perform operations on resources.

A RESTful API follows these principles:

  • Stateless: No client information is stored on the server between requests.
  • Client-Server Architecture: The client and server operate independently.
  • Use of HTTP Methods:
    • GET - Retrieve data
    • POST - Create new data
    • PUT - Update existing data
    • DELETE - Remove data
  • Resource-Based URLs: URLs represent resources (e.g., /users, /products).
  • JSON Format: REST APIs typically use JSON (JavaScript Object Notation) to exchange data.

2. Setting Up the Development Environment

Before building a RESTful API, install the necessary tools:

1.   Install Node.js and npm (if not already installed)
Download from https://nodejs.org.

2.   Initialize a Node.js Project

bash
mkdir restful-api
cd restful-api
npm init -y

3.   Install Express.js (a web framework for Node.js)

bash
npm install express

4.   Install additional dependencies:

o    nodemon (for automatic server restart)

o    body-parser (for parsing request bodies)

o    cors (for enabling cross-origin requests)

bash
npm install nodemon body-parser cors

5.   Modify package.json to enable automatic server restart:

json
"scripts": {
  "start": "node index.js",
  "dev": "nodemon index.js"
}

3. Designing a RESTful API

We will design an API to manage products with the following endpoints:

Method

Endpoint

Description

GET

/products

Get all products

GET

/products/:id

Get a single product

POST

/products

Create a new product

PUT

/products/:id

Update a product

DELETE

/products/:id

Delete a product

Data Model

Each product will have:

  • id (Unique identifier)
  • name (Product name)
  • price (Product price)
  • description (Product details)

Example JSON structure:

json
{
  "id": 1,
  "name": "Laptop",
  "price": 75000,
  "description": "A high-performance laptop"
}

4. Implementing CRUD Operations in Express

Step 1: Create the Server (index.js)

javascript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
 
const app = express();
const PORT = 5000;
 
// Middleware
app.use(cors());
app.use(bodyParser.json());
 
// Sample data (in-memory database)
let products = [
    { id: 1, name: "Laptop", price: 75000, description: "A high-performance laptop" },
    { id: 2, name: "Smartphone", price: 25000, description: "A flagship smartphone" }
];
 
// Root route
app.get('/', (req, res) => {
    res.send('Welcome to the RESTful API');
});
 
// Start the server
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

Step 2: Implement CRUD Routes

1. Get All Products (GET /products)

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

2. Get a Single Product by ID (GET /products/:id)

javascript
app.get('/products/:id', (req, res) => {
    const product = products.find(p => p.id === parseInt(req.params.id));
    if (!product) return res.status(404).json({ message: "Product not found" });
    res.json(product);
});

3. Create a New Product (POST /products)

javascript
app.post('/products', (req, res) => {
    const newProduct = {
        id: products.length + 1,
        name: req.body.name,
        price: req.body.price,
        description: req.body.description
    };
    products.push(newProduct);
    res.status(201).json(newProduct);
});

4. Update an Existing Product (PUT /products/:id)

javascript
app.put('/products/:id', (req, res) => {
    const product = products.find(p => p.id === parseInt(req.params.id));
    if (!product) return res.status(404).json({ message: "Product not found" });
 
    product.name = req.body.name;
    product.price = req.body.price;
    product.description = req.body.description;
    res.json(product);
});

5. Delete a Product (DELETE /products/:id)

javascript
app.delete('/products/:id', (req, res) => {
    products = products.filter(p => p.id !== parseInt(req.params.id));
    res.json({ message: "Product deleted successfully" });
});

5. Testing the API

Using Postman or cURL

1.   Start the server

bash
npm run dev

2.   Test API Endpoints:

o    GET /products → Returns all products.

o    GET /products/1 → Returns product with id=1.

o    POST /products → Sends new product data.

o    PUT /products/1 → Updates product with id=1.

o    DELETE /products/1 → Deletes product with id=1.


6. Conclusion

  • RESTful APIs use HTTP methods to handle requests.
  • Express.js simplifies server creation.
  • Middleware (body-parser, cors) is important for handling requests.
  • Testing using Postman helps validate API functionality.

By following these steps, you have successfully built a RESTful API with Node.js and Express.js that performs CRUD operations on a product resource. 🚀


7. Lab Tasks

1.   Modify the API to manage users instead of products.

2.   Implement error handling (e.g., validation for empty fields).

3.   Connect the API to a MongoDB database using Mongoose.


Would you like additional topics, such as database integration with MongoDB or JWT authentication? 😊

You said:

write solution..7. Lab Tasks Modify the API to manage users instead of products. Implement error handling (e.g., validation for empty fields). Connect the API to a MongoDB database using Mongoose.

ChatGPT said:

ChatGPT

Here’s a complete solution for the Lab Tasks where we modify the RESTful API to manage users instead of products, implement error handling, and connect it to MongoDB using Mongoose.


Step 1: Install Dependencies

Before starting, install the required Node.js packages.

bash
npm install express mongoose body-parser cors dotenv
  • express → Web framework for Node.js
  • mongoose → MongoDB ODM (Object Data Modeling)
  • body-parser → Parses incoming JSON data
  • cors → Enables cross-origin requests
  • dotenv → Loads environment variables

Step 2: Setup MongoDB Connection

1. Create a .env file for database credentials:

makefile
MONGO_URI=mongodb://127.0.0.1:27017/userdb
PORT=5000

2. Create db.js to handle MongoDB connection

javascript
const mongoose = require('mongoose');
require('dotenv').config();
 
const connectDB = async () => {
    try {
        await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log("MongoDB Connected...");
    } catch (err) {
        console.error("Database Connection Error:", err);
        process.exit(1);
    }
};
 
module.exports = connectDB;

Step 3: Define the User Model

Create models/User.js

javascript
const mongoose = require('mongoose');
 
const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Name is required"],
        trim: true
    },
    email: {
        type: String,
        required: [true, "Email is required"],
        unique: true,
        match: [/.+\@.+\..+/, "Please enter a valid email address"]
    },
    age: {
        type: Number,
        required: [true, "Age is required"],
        min: [1, "Age must be at least 1"]
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});
 
module.exports = mongoose.model('User', UserSchema);

Step 4: Implement CRUD Operations with Error Handling

Create routes/userRoutes.js

javascript
const express = require('express');
const User = require('../models/User');
 
const router = express.Router();
 
// 1. Get all users
router.get('/', async (req, res) => {
    try {
        const users = await User.find();
        res.json(users);
    } catch (err) {
        res.status(500).json({ error: "Server Error" });
    }
});
 
// 2. Get user by ID
router.get('/:id', async (req, res) => {
    try {
        const user = await User.findById(req.params.id);
        if (!user) return res.status(404).json({ error: "User not found" });
        res.json(user);
    } catch (err) {
        res.status(500).json({ error: "Invalid User ID" });
    }
});
 
// 3. Create new user
router.post('/', async (req, res) => {
    try {
        const { name, email, age } = req.body;
        if (!name || !email || !age) {
            return res.status(400).json({ error: "All fields are required" });
        }
 
        const newUser = new User({ name, email, age });
        await newUser.save();
        res.status(201).json(newUser);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
});
 
// 4. Update user
router.put('/:id', async (req, res) => {
    try {
        const { name, email, age } = req.body;
        if (!name || !email || !age) {
            return res.status(400).json({ error: "All fields are required" });
        }
 
        const updatedUser = await User.findByIdAndUpdate(
            req.params.id,
            { name, email, age },
            { new: true, runValidators: true }
        );
 
        if (!updatedUser) return res.status(404).json({ error: "User not found" });
 
        res.json(updatedUser);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
});
 
// 5. Delete user
router.delete('/:id', async (req, res) => {
    try {
        const user = await User.findByIdAndDelete(req.params.id);
        if (!user) return res.status(404).json({ error: "User not found" });
 
        res.json({ message: "User deleted successfully" });
    } catch (err) {
        res.status(500).json({ error: "Invalid User ID" });
    }
});
 
module.exports = router;

Step 5: Setup Express Server

Modify index.js

javascript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const connectDB = require('./db');
const userRoutes = require('./routes/userRoutes');
 
const app = express();
const PORT = process.env.PORT || 5000;
 
// Connect to MongoDB
connectDB();
 
// Middleware
app.use(cors());
app.use(bodyParser.json());
 
// Routes
app.use('/users', userRoutes);
 
app.get('/', (req, res) => {
    res.send("Welcome to User API");
});
 
// Start server
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

Step 6: Testing the API

Start the server

bash
npm run dev

Test API Endpoints using Postman or cURL

Method

Endpoint

Description

GET

/users

Get all users

GET

/users/:id

Get a single user

POST

/users

Create a new user

PUT

/users/:id

Update a user

DELETE

/users/:id

Delete a user

Example cURL Requests

1.   Create a new user

bash
curl -X POST http://localhost:5000/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com", "age": 25}'

2.   Get all users

bash
curl -X GET http://localhost:5000/users

3.   Update a user

bash
curl -X PUT http://localhost:5000/users/USER_ID -H "Content-Type: application/json" -d '{"name": "John Updated", "email": "johnupdated@example.com", "age": 26}'

4.   Delete a user

bash
curl -X DELETE http://localhost:5000/users/USER_ID

Summary

Modified API to manage users
Implemented error handling for validation
Connected API to MongoDB using Mongoose
Tested endpoints using Postman/cURL


Next Steps

🔹 Add Authentication (JWT) for secure user login
🔹 Use Swagger for API Documentation
🔹 Deploy API using cloud platforms like Heroku or AWS

Here are 10 assignments with detailed step-by-step solutions for Class 26: Building a RESTful API. These assignments cover the key concepts of designing and implementing CRUD operations using Node.js and Express.


Assignment 1: Designing a RESTful API for Users

Objective: Design a RESTful API for managing users.

Solution:

1.   Define the resources: The resource we are managing is users. The user data will include properties like id, name, email, and age.

2.   Define the endpoints:

o    GET /users: Fetch all users.

o    GET /users/{id}: Fetch a specific user by ID.

o    POST /users: Create a new user.

o    PUT /users/{id}: Update an existing user by ID.

o    DELETE /users/{id}: Delete a user by ID.

3.   API Response Format:

o    All responses should be in JSON format.

o    Successful responses should have a status code and a message.

4.   Set up the routes:

o    /users for getting all users (GET), adding a new user (POST).

o    /users/{id} for getting a specific user (GET), updating (PUT), and deleting (DELETE).


Assignment 2: Setting Up Node.js with Express

Objective: Set up a basic Node.js and Express app for the RESTful API.

Solution:

1.   Install Node.js and Express:

o    Open the terminal and initialize a new Node.js project:

bash
npm init -y
npm install express

2.   Create the app:

o    In the index.js file, set up the basic Express app:

js
const express = require('express');
const app = express();
 
app.use(express.json()); // To parse JSON request body
 
app.listen(3000, () => {
  console.log('Server running on port 3000');
});

3.   Run the server:

o    In the terminal, run the server:

bash
node index.js

Assignment 3: Creating a User Model

Objective: Create a simple in-memory model for storing users.

Solution:

1.   Create a User model:

o    For simplicity, use an array to store users in users.js:

js
let users = [];
 
function getAllUsers() {
  return users;
}
 
function getUserById(id) {
  return users.find(user => user.id === id);
}
 
function createUser(user) {
  users.push(user);
  return user;
}
 
function updateUser(id, updatedUser) {
  const index = users.findIndex(user => user.id === id);
  if (index !== -1) {
    users[index] = { ...users[index], ...updatedUser };
    return users[index];
  }
  return null;
}
 
function deleteUser(id) {
  const index = users.findIndex(user => user.id === id);
  if (index !== -1) {
    return users.splice(index, 1);
  }
  return null;
}
 
module.exports = { getAllUsers, getUserById, createUser, updateUser, deleteUser };

Assignment 4: Implementing GET /users Endpoint

Objective: Implement the endpoint to fetch all users.

Solution:

1.   Create a route:

o    In index.js, add the following route to fetch all users:

js
const { getAllUsers } = require('./users');
 
app.get('/users', (req, res) => {
  const allUsers = getAllUsers();
  res.json({ status: 'success', data: allUsers });
});

2.   Test the endpoint:

o    Use Postman or curl to test the GET /users endpoint.


Assignment 5: Implementing GET /users/{id} Endpoint

Objective: Implement the endpoint to fetch a specific user by ID.

Solution:

1.   Create a route:

o    In index.js, add the following route:

js
const { getUserById } = require('./users');
 
app.get('/users/:id', (req, res) => {
  const user = getUserById(Number(req.params.id));
  if (user) {
    res.json({ status: 'success', data: user });
  } else {
    res.status(404).json({ status: 'error', message: 'User not found' });
  }
});

2.   Test the endpoint:

o    Test GET /users/1 using Postman or curl.


Assignment 6: Implementing POST /users Endpoint

Objective: Implement the endpoint to create a new user.

Solution:

1.   Create a route:

o    In index.js, add the following route:

js
const { createUser } = require('./users');
 
app.post('/users', (req, res) => {
  const { name, email, age } = req.body;
  const newUser = { id: Date.now(), name, email, age };
  createUser(newUser);
  res.status(201).json({ status: 'success', data: newUser });
});

2.   Test the endpoint:

o    Test POST /users using Postman with a JSON body:

json
{
  "name": "John Doe",
  "email": "john@example.com",
  "age": 30
}

Assignment 7: Implementing PUT /users/{id} Endpoint

Objective: Implement the endpoint to update an existing user.

Solution:

1.   Create a route:

o    In index.js, add the following route:

js
const { updateUser } = require('./users');
 
app.put('/users/:id', (req, res) => {
  const updatedUser = updateUser(Number(req.params.id), req.body);
  if (updatedUser) {
    res.json({ status: 'success', data: updatedUser });
  } else {
    res.status(404).json({ status: 'error', message: 'User not found' });
  }
});

2.   Test the endpoint:

o    Test PUT /users/1 using Postman with a JSON body to update a user.


Assignment 8: Implementing DELETE /users/{id} Endpoint

Objective: Implement the endpoint to delete a user.

Solution:

1.   Create a route:

o    In index.js, add the following route:

js
const { deleteUser } = require('./users');
 
app.delete('/users/:id', (req, res) => {
  const deletedUser = deleteUser(Number(req.params.id));
  if (deletedUser) {
    res.json({ status: 'success', data: deletedUser });
  } else {
    res.status(404).json({ status: 'error', message: 'User not found' });
  }
});

2.   Test the endpoint:

o    Test DELETE /users/1 using Postman or curl.


Assignment 9: Implementing Error Handling in the API

Objective: Implement error handling for invalid routes and invalid data.

Solution:

1.   Handle invalid routes:

o    Add a middleware for handling undefined routes:

js
app.use((req, res, next) => {
  res.status(404).json({ status: 'error', message: 'Route not found' });
});

2.   Handle invalid input data:

o    Use input validation with middleware (e.g., checking required fields):

js
function validateUserInput(req, res, next) {
  const { name, email, age } = req.body;
  if (!name || !email || !age) {
    return res.status(400).json({ status: 'error', message: 'Missing required fields' });
  }
  next();
}
 
app.post('/users', validateUserInput, (req, res) => {
  // Proceed with creating the user...
});

Assignment 10: Writing Tests for the API

Objective: Write simple tests for the API endpoints.

Solution:

1.   Install testing tools:

o    Install Mocha and Chai for testing:

bash
npm install mocha chai chai-http --save-dev

2.   Write tests:

o    Create a test.js file:

js
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('./index');
chai.use(chaiHttp);
const { expect } = chai;
 
describe('Users API', () => {
  it('should GET all users', done => {
    chai.request(server)
      .get('/users')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        done();
      });
  });
 
  it('should POST a new user', done => {
    const user = { name: 'Jane Doe', email: 'jane@example.com', age: 25 };
    chai.request(server)
      .post('/users')
      .send(user)
      .end((err, res) => {
        expect(res.status).to.equal(201);
        expect(res.body.data.name).to.equal('Jane Doe');
        done();
      });
  });
});

3.   Run tests:

o    Run tests using Mocha:

bash
npx mocha test.js

These assignments will help students understand and implement a RESTful API step by step with proper error handling and testing.

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 concept of building a RESTful API using Node.js and Express, with detailed explanations for each.


MCQs:

1. What does "REST" stand for in RESTful APIs?

a) Resource Execution Standard Technology
b) Representational State Transfer
c) Reliable System for External Transfers
d) Randomized State Transfer

Explanation: REST stands for Representational State Transfer, which is an architectural style for designing networked applications.


2. Which HTTP method is used to retrieve data from a RESTful API?

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

Explanation: The GET method is used to retrieve data from a server.


3. Which HTTP status code represents a successful request for data?

a) 200 OK
b) 404 Not Found
c) 500 Internal Server Error
d) 400 Bad Request

Explanation: 200 OK indicates that the request was successful.


4. Which of the following HTTP methods is used to delete a resource in a RESTful API?

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

Explanation: DELETE is used to remove a resource from the server.


5. In RESTful API design, what does a resource typically refer to?

a) A server
b) A URL endpoint
c) A database
d) A file system

Explanation: A resource typically refers to the data or object being managed, which is usually identified by a URL endpoint.


6. What is the purpose of the HTTP POST method in RESTful APIs?

a) To update data
b) To retrieve data
c) To delete data
d) To create data

Explanation: POST is used to create new resources on the server.


7. What is the main difference between PUT and PATCH methods in RESTful APIs?

a) PUT replaces the entire resource, while PATCH updates part of the resource
b) PUT is used to delete resources, while PATCH creates them
c) PUT is used only for updating, while PATCH creates new resources
d) PUT and PATCH are the same

Explanation: PUT replaces the entire resource, while PATCH only updates part of it.


8. Which of the following is NOT a characteristic of RESTful APIs?

a) Stateless
b) Client-server architecture
c) Requires the client to maintain the session
d) Uses HTTP methods

Explanation: RESTful APIs are stateless, meaning the server does not store the client's state between requests.


9. Which library is commonly used to build RESTful APIs in Node.js?

a) Axios
b) Express
c) React
d) jQuery

Explanation: Express is a popular Node.js framework used for building RESTful APIs.


10. What does the status code 404 indicate in a RESTful API?

a) Success
b) Bad Request
c) Not Found
d) Internal Server Error

Explanation: 404 Not Found indicates that the requested resource could not be found.


11. What is the primary purpose of the express.json() middleware in Node.js?

a) To parse incoming URL-encoded data
b) To parse incoming JSON request bodies
c) To parse incoming query parameters
d) To parse cookies

Explanation: express.json() is used to parse incoming JSON data from the request body.


12. Which of the following is the correct syntax to create a new Express application?

a) const app = require('express')();
b) const app = express();
c) app = new express();
d) const app = express.create();

Explanation: The correct syntax is const app = express(); to initialize a new Express app.


13. What is the typical status code for a successful resource creation using POST?

a) 200 OK
b) 201 Created
c) 204 No Content
d) 400 Bad Request

Explanation: 201 Created is the status code returned when a resource is successfully created.


14. In the context of REST, what does the term "stateless" mean?

a) The server stores the user's session
b) The server does not maintain any client context between requests
c) The client stores the session
d) The server stores the client's data permanently

Explanation: Stateless means that the server does not store any context between requests, and each request is independent.


15. What is the role of the req.body object in Express?

a) It contains the HTTP response data
b) It contains the request data sent by the client
c) It contains the HTTP status code
d) It contains the query parameters

Explanation: req.body contains the data sent by the client in the request body, usually in POST or PUT requests.


16. What is the purpose of using middleware in Express?

a) To handle HTTP status codes
b) To define routes
c) To handle functions before the request is processed
d) To parse URLs

Explanation: Middleware functions are used to process requests before they are passed to route handlers, such as parsing request bodies or handling authentication.


17. What is the default port for an Express server to run on?

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

Explanation: The default port for an Express server is 3000, unless specified otherwise.


18. How do you define a route for a GET request in Express?

a) app.get('/path', handler);
b) app.route('/path').get(handler);
c) Both a and b
d) None of the above

Explanation: Both a and b are valid ways to define a route for a GET request in Express.


19. In which scenario would you use the HTTP PUT method in a RESTful API?

a) To fetch all users
b) To update the entire resource
c) To create a new user
d) To delete a resource

Explanation: PUT is used to update an entire resource on the server.


20. How can you access route parameters in Express?

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

Explanation: req.params is used to access route parameters in Express.


21. What type of data format is typically returned by a RESTful API?

a) HTML
b) XML
c) JSON
d) Plain text

Explanation: JSON is the most common data format returned by RESTful APIs.


22. What does HTTP status code 500 represent?

a) OK
b) Created
c) Internal Server Error
d) Not Found

Explanation: 500 Internal Server Error indicates that something went wrong on the server side.


23. Which of the following is the correct way to start an Express server?

a) server.listen(3000)
b) app.start(3000)
c) app.listen(3000)
d) express.listen(3000)

Explanation: The correct method to start an Express server is app.listen(3000).


24. What is a common use of middleware in an Express API?

a) Handling requests for static files
b) Parsing request bodies
c) Handling authentication
d) All of the above

Explanation: Middleware can be used for many purposes, including parsing request bodies, handling authentication, and serving static files.


25. What type of method is typically used for an endpoint that updates an existing resource?

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

Explanation: PUT is used to update an existing resource.


26. What is the response format for a successful POST request to create a new resource?

a) A 200 status code with a message
b) A 201 status code with the created resource
c) A 404 status code with an error message
d) A 400 status code with an error message

Explanation: A 201 status code is used for successful resource creation, and the created resource is often returned in the response body.


27. Which method would you use to update a specific user by ID in a RESTful API?

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

Explanation: PUT is used to update an existing resource, such as a user by their ID.


28. How would you define a POST route in Express?

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

Explanation: The correct syntax to define a POST route is app.post('/path', handler);.


29. What is a common error that should be handled when implementing a RESTful API?

a) Invalid data in the request body
b) Invalid request method
c) Resource not found
d) All of the above

Explanation: Handling errors such as invalid data, invalid methods, and resource not found is critical when building RESTful APIs.


30. What does the req.query object contain in an Express API?

a) The body of the request
b) The route parameters
c) The query parameters from the URL
d) The response data

Explanation: req.query contains the query parameters from the URL.


31. What does an API endpoint typically include?

a) HTTP method
b) URL
c) Request body
d) All of the above

Explanation: An API endpoint includes the HTTP method, URL, and sometimes a request body for passing data.


32. How would you define a route that listens for DELETE requests in Express?

a) app.delete('/path', handler);
b) app.delete('/path').handler();
c) app.route('/path').delete(handler);
d) None of the above

Explanation: The correct way to define a DELETE route is app.delete('/path', handler);.


33. What is the correct HTTP method to retrieve a list of all users from a RESTful API?

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

Explanation: GET is used to retrieve a list of resources, such as users.


34. How does Express handle route parameters in URL paths?

a) Using the query string
b) By including the parameter in the request body
c) By including the parameter in the URL, prefixed with a colon (e.g., /user/:id)
d) By adding parameters as headers

Explanation: Express uses colon-prefixed parameters in the URL to define route parameters, e.g., /user/:id.


35. How can you handle a 404 error in Express when a route does not match?

a) By using app.use() middleware
b) By using a custom error-handling middleware
c) By returning a 200 status code
d) Both a and b

Explanation: You can use custom middleware or error-handling middleware to catch 404 errors in Express.


36. What does the HTTP status code 401 indicate?

a) Unauthorized
b) Internal Server Error
c) Forbidden
d) Not Found

Explanation: 401 Unauthorized indicates that the user is not authorized to access the requested resource.


37. What is the primary purpose of a RESTful API?

a) To manage server resources
b) To allow clients to interact with server data via HTTP requests
c) To improve server performance
d) To store data locally

Explanation: The primary purpose of a RESTful API is to allow clients to interact with server data via HTTP requests.


38. What is the difference between PUT and PATCH in terms of updating resources?

a) PUT updates the entire resource, PATCH updates part of the resource
b) PUT deletes a resource, PATCH creates a new resource
c) PATCH is used for retrieving data, PUT for deleting
d) PUT and PATCH are interchangeable

Explanation: PUT replaces the entire resource, while PATCH only updates part of it.


39. How would you handle validation in a RESTful API using Express?

a) By using a validation library like Joi
b) By manually checking data in the route handler
c) Both a and b
d) Neither a nor b

Explanation: Both methods can be used, but libraries like Joi help automate the process.


40. How do you send a response back to the client with JSON data in Express?

a) res.send({ data: 'value' });
b) res.json({ data: 'value' });
c) res.status(200).send({ data: 'value' });
d) All of the above

Explanation: res.json() is typically used to send JSON data, and other methods also work, depending on the use case.


41. What is the benefit of using RESTful architecture in API design?

a) It promotes scalability
b) It is easier to maintain
c) It allows stateless communication
d) All of the above

Explanation: RESTful architecture is scalable, maintainable, and stateless, making it a flexible and efficient choice for APIs.


42. What is the role of the res.status() method in Express?

a) It sets the response body
b) It sets the response status code
c) It defines the route
d) It handles the request body

Explanation: The res.status() method is used to set the HTTP status code for the response.


43. Which status code is used to indicate a successful PUT request?

a) 200 OK
b) 204 No Content
c) 201 Created
d) 400 Bad Request

Explanation: 200 OK or 204 No Content can indicate success for a PUT request.


44. In a RESTful API, what is typically returned when a DELETE request is successful?

a) 200 OK with a success message
b) 204 No Content with no data
c) 404 Not Found
d) 400 Bad Request

Explanation: A successful DELETE request typically returns 204 No Content.


45. What does the req.method property contain in Express?

a) The HTTP status code
b) The HTTP method (GET, POST, etc.) used in the request
c) The request body
d) The route parameters

Explanation: req.method contains the HTTP method used for the request, such as GET, POST, etc.


46. Which status code is returned when a client sends an invalid request to a RESTful API?

a) 400 Bad Request
b) 401 Unauthorized
c) 403 Forbidden
d) 404 Not Found

Explanation: 400 Bad Request is returned when the server cannot process an invalid request.


47. How would you define a route for multiple HTTP methods in Express?

a) app.route('/path').all(handler);
b) app.route('/path').method(handler);
c) app.method('/path', handler);
d) app.all('/path', handler);

Explanation: You can define routes for multiple methods using app.route('/path') followed by the method name.


48. Which library can be used to handle asynchronous requests and promises in Node.js for a RESTful API?

a) Axios
b) Express
c) Promise
d) jQuery

Explanation: Axios is commonly used for handling asynchronous requests and promises in Node.js.


49. What type of testing is essential for RESTful APIs?

a) Unit testing
b) Integration testing
c) End-to-end testing
d) All of the above

Explanation: All types of testing are important to ensure the RESTful API is functioning as expected.


50. What is a RESTful API endpoint typically made up of?

a) HTTP Method
b) Resource URL
c) Request/Response format
d) All of the above

Explanation: A RESTful API endpoint includes the HTTP Method, Resource URL, and typically the Request/Response format (like JSON). 

No comments:

Post a Comment

Search This Blog

Powered by Blogger.