Chapter 5: Request and Response Formats
Chapter 5 of 14
Chapter 5: Request and Response Formats
5.1 JSON Format
JSON (JavaScript Object Notation) is the standard format for REST API communication.
// Request body (POST/PUT/PATCH)
{
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
// Response format
{
"success": true,
"data": {
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
}
// Error response
{
"success": false,
"error": {
"message": "Validation failed",
"code": "VALIDATION_ERROR",
"details": [
{ "field": "email", "message": "Invalid email format" }
]
}
}
5.2 Content Negotiation
// Accept different formats
app.get('/api/users/:id', (req, res) => {
const accept = req.headers.accept;
if (accept.includes('application/xml')) {
res.type('xml');
res.send(convertToXML(user));
} else {
res.json(user);
}
});
5.3 Request Validation
// Validate request body
const { body, validationResult } = require('express-validator');
app.post('/api/users',
body('email').isEmail().normalizeEmail(),
body('name').trim().isLength({ min: 2, max: 50 }),
body('age').isInt({ min: 0, max: 120 }),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process valid request
}
);