Which URL correctly represents version 2 of an API using URL path versioning?
URL path versioning places the version number directly in the URL path.
URL path versioning includes the version number as a segment in the URL path, like /api/v2/. This makes it clear and easy to route requests.
Given an Express.js API that uses a custom header X-API-Version to determine the API version, what happens if the header is missing?
app.use((req, res, next) => {
const version = req.headers['x-api-version'] || '1';
req.apiVersion = version;
next();
});
app.get('/data', (req, res) => {
if (req.apiVersion === '2') {
res.send('Data from version 2');
} else {
res.send('Data from version 1');
}
});Look at how the version is assigned when the header is missing.
The middleware sets req.apiVersion to '1' if the header is missing, so the API responds with version 1 data by default.
Which Express.js route handler correctly reads the API version from a query parameter version and sends a response accordingly?
app.get('/info', (req, res) => {
// Your code here
});Query parameters are accessed via req.query in Express.js.
Query parameters are part of the URL after ? and are accessed using req.query. Using req.params accesses route parameters, req.body accesses POST data, and headers are in req.headers.
Consider this Express.js middleware that reads API version from the Accept header:
app.use((req, res, next) => {
const accept = req.headers.accept;
const versionMatch = accept.match(/application\/vnd\.myapi\.v(\d+)\+json/);
req.apiVersion = versionMatch ? versionMatch[1] : '1';
next();
});What error will occur if the Accept header is missing?
Consider what happens when accept is undefined and you call match on it.
If the Accept header is missing, accept is undefined. Calling match on undefined causes a TypeError: Cannot read properties of undefined (reading 'match').
Given this Express.js middleware chain, what will be the final response when a request is made to /resource with header X-API-Version: 3?
app.use((req, res, next) => {
req.apiVersion = '1';
next();
});
app.use((req, res, next) => {
if(req.headers['x-api-version']) {
req.apiVersion = req.headers['x-api-version'];
}
next();
});
app.get('/resource', (req, res) => {
res.send(`API version is ${req.apiVersion}`);
});Think about the order of middleware and how they modify req.apiVersion.
The first middleware sets req.apiVersion to '1'. The second middleware checks for the header and overrides req.apiVersion with '3'. The final handler sends 'API version is 3'.