4 min read
ā¢Question 19 of 28mediumWhat is content negotiation in APIs?
Understanding content negotiation.
What You'll Learn
- What content negotiation is
- Accept and Content-Type headers
- Implementation
What is Content Negotiation?
Content negotiation allows clients and servers to agree on the format of data being exchanged.
Key Headers
Accept (Client ā Server)
code.jsJavaScript
Accept: application/json
Accept: application/xml
Accept: text/html, application/json;q=0.9Content-Type (Both directions)
code.jsJavaScript
Content-Type: application/json
Content-Type: application/xml
Content-Type: multipart/form-dataQuality Values (q)
code.jsJavaScript
Accept: application/json;q=1.0, application/xml;q=0.8, */*;q=0.1
// Server preference order:
// 1. JSON (q=1.0)
// 2. XML (q=0.8)
// 3. Anything else (q=0.1)Implementation
code.jsJavaScript
app.get('/users', (req, res) => {
const users = [{ id: 1, name: 'John' }];
// Check Accept header
const accept = req.accepts(['json', 'xml', 'html']);
switch (accept) {
case 'json':
res.json(users);
break;
case 'xml':
res.type('xml').send(convertToXML(users));
break;
case 'html':
res.render('users', { users });
break;
default:
res.status(406).send('Not Acceptable');
}
});