Advanced Backend Coding Questions - Web Programming Final Exam
Q1. Build a RESTful API Endpoint with Validation
Route: POST /api/transactions
- Validates required fields: date, expenseType, description, amount
- Returns 400 if validation fails, 201 if successful
Code:
[Link]('/api/transactions', async (req, res) => {
const { date, expenseType, description, amount } = [Link];
if (!date || !expenseType || !description || !amount) {
return [Link](400).json({ error: 'All fields are required' });
}
try {
const newTransaction = await [Link]([Link]);
[Link](201).json(newTransaction);
} catch (err) {
[Link](500).json({ error: 'Server error', details: [Link] });
}
})
Q2. Handle Non-Existent Resources Gracefully
Route: GET /transactions/:id
- Returns 404 if no transaction is found, or 400 if ID is invalid
Code:
[Link]('/transactions/:id', async (req, res) => {
try {
const txn = await [Link]([Link]);
if (!txn) return [Link](404).send('Transaction not found');
[Link]('transactionDetails', { txn });
} catch (err) {
[Link](400).send('Invalid ID');
}
})
Q3. Global Error Handling Middleware
Error Middleware:
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).json({ status: 'error', message: [Link] || 'Unexpected server error' });
});
Usage:
[Link]('/fail', (req, res) => {
throw new Error('Manual crash');
});
Q4. Custom Mongoose Validation Errors
Model Schema:
amount: {
type: Number,
required: true,
validate: {
validator: value => value > 0,
message: 'Amount must be greater than zero.'
}
}
API Integration:
if ([Link] === 'ValidationError') {
return [Link](400).json({ error: [Link] });
}
Q5. Add Filtering Query Parameters to API
Route: GET /api/transactions?expenseType=Food
Code:
[Link]('/api/transactions', async (req, res) => {
try {
const filter = {};
if ([Link]) {
[Link] = [Link];
}
const txns = await [Link](filter);
[Link](txns);
} catch (err) {
[Link](500).json({ error: 'Server error' });
}
});
Q6. Toggle Status with PATCH
Route: PATCH /transactions/:id/toggle-status
Code:
[Link]('/transactions/:id/toggle-status', async (req, res) => {
try {
const txn = await [Link]([Link]);
if (!txn) return [Link](404).send('Transaction not found');
[Link] = ![Link];
await [Link]();
[Link](txn);
} catch (err) {
[Link](400).send('Invalid ID');
}
});
Q7. Delete with Confirmation Response
Route: DELETE /api/transactions/:id
Code:
[Link]('/api/transactions/:id', async (req, res) => {
try {
const txn = await [Link]([Link]);
if (!txn) return [Link](404).json({ error: 'Transaction not found' });
[Link]({ message: 'Transaction successfully deleted', txn });
} catch (err) {
[Link](400).json({ error: 'Invalid ID format' });
}
});