Consider a REST API that uses URL path versioning. The client requests /api/v2/users. The server code routes this to the version 2 handler, which returns a JSON list of users with an added email field.
What JSON response will the client receive?
def get_users(version): if version == 'v1': return [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}] elif version == 'v2': return [{'id': 1, 'name': 'Alice', 'email': 'alice@example.com'}, {'id': 2, 'name': 'Bob', 'email': 'bob@example.com'}] response = get_users('v2') print(response)
Check which version the function returns with the email field included.
Version 2 adds the email field to each user. Since the client requested v2, the response includes emails.
There are several ways to version REST APIs: URL path versioning, query parameter versioning, and header versioning.
Which method is generally considered best for maintaining backward compatibility and clean URLs?
Think about what makes URLs clear and easy to cache.
URL path versioning clearly separates versions and is easy to cache and document, making it best for backward compatibility.
The following Python code tries to parse the API version from a header and route the request. It returns 'default handler' even though the header has value 2. Why?
def route_request(headers): version = headers.get('X-API-Version') if version == '1': return 'v1 handler' elif version == '2': return 'v2 handler' else: return 'default handler' headers = {'X-API-Version': 2} print(route_request(headers))
Check the type of the header value and how it is compared.
The header value is an integer 2, but the code compares it to strings '1' and '2'. Since 2 == '2' is False, it falls to the 'default handler'.
Given Flask web framework, which route decorator correctly defines a versioned API endpoint for version 1?
from flask import Flask app = Flask(__name__) @app.route('/api/v1/users') def get_users(): return 'Users v1'
Think about how URL paths are defined in Flask routes.
Flask routes match URL paths literally. Version in the path should come before the resource name for clarity.
Consider this API versioning logic in pseudocode:
if 'version' in request.headers:
if request.headers['version'] in ['1', '2', '3']:
use that version
else:
use default version 1
else:
use default version 1How many distinct API versions can clients explicitly request?
Count the versions listed in the allowed list.
The code allows clients to request versions '1', '2', or '3' explicitly. Any other or missing version defaults to '1'.