Explore the differences and appropriate uses of path and query parameters in RESTful API design. This quiz challenges your grasp of REST URI conventions, parameter usage, and best practices with practical examples and scenarios.
In the REST URL '/users/123/profile?verbose=true', which part represents a path parameter?
Explanation: In this URL, '123' is a path parameter, as it identifies a specific user within the endpoint path. 'users' is part of the resource path but not a variable parameter. 'verbose' and 'true' are part of the query string, with 'verbose' being the key and 'true' its value. Path parameters typically appear between slashes in the URL path.
Which is the primary use of query parameters in RESTful APIs, as shown in the example '/items?color=blueu0026limit=10'?
Explanation: Query parameters in REST are mainly used for filtering, sorting, and customizing the responses, like choosing color or limiting the number of items returned. They are not meant for defining resource types ('To define the resource type'), specifying API versions ('To specify the API version'), or uniquely identifying a resource ('To identify a unique resource'). Path parameters are usually used for unique identification.
When designing a RESTful endpoint to fetch a user by their unique ID, which URL structure correctly places the user ID as a path parameter?
Explanation: The '/user/45' format correctly uses the path parameter to uniquely identify the user in the endpoint path, reflecting the entity's identity. The '/user?id=45' and '/user?user=45' structures use query parameters, which are typically for filtering rather than identification. The '/user/id/45?details=full' can be valid, but adding 'id' in the path is redundant when the resource itself is identified by the immediate following segment.
Given the endpoint '/products/678/reviews?rating=5', what is the role of the '678' and 'rating=5' values?
Explanation: '678' is a path parameter that specifies the product for which reviews are being accessed. 'rating=5' is a query parameter that filters the reviews to only those with a rating of 5. The distractors mix up their purposes or incorrectly state that both serve the same function.
How should multiple resource identifiers, like order ID and item ID, typically be represented in a RESTful path?
Explanation: Using '/order/21/item/7' places both the order ID and item ID as path parameters, clearly representing hierarchical resource relationships. Query parameters, as in '/order?orderId=21u0026itemId=7', are usually for filtering or modifying the request but not for unique identification. The formats '/order/items/21:7' and '/order-items/21-7' misuse delimiting and do not clearly communicate the relationship between resources as the REST convention prefers.