What are Path Parameters?
Path is a type of parameter that lives within the endpoint URI. In a typical REST scheme, the path portion of the URL represents entity class hierarchy.
Path parameters help to scope the call down to one single resource, thereby saving you the trouble of having to build a body to deliver something as simple as a resource finder.
Path parameters are surrounded with curly brackets and offer a unique opportunity for developers to control the representation of a specific resource.
For Example:
Here is an endpoint used to retrieve resource data on a VMware virtual machine:
/vmware/vm/{id}
The {id}
part represents the parameter that is required for the call.
Path parameters with many objects can be serialized in several ways:
- Path-style expansion (matrix), using semicolon such as /map/point; x=50;y=20
- Label expansion – using dots, such as /color. R=50.G=150.B=100
- Comma-delimited style such as /users/12,34,56
However, the path style expansion is the commonly used serialization method.
Path vs. Query Parameters
While Path and Query parameters seem subtly similar, they have vast differences:
1. For starts, order matters in path parameters.
Unlike query string parameters where the order doesn’t matter, path parameters values must be given in correspondence with the format that is dictated by the URL path.
For instance, if the service path dictates “/resource/noun/ format/ value/verb,” you shouldn’t interchange it with “resource/format/value/noun/ verb” when using path parameters.
2. You can’t omit path parameter values.
While query parameters allow you to omit a value, path parameter values can’t be omitted since it would mean changing the URL path. However, the last parameter value is exempted since you can either add or remove a value at the end of the URL path.
3. Path parameters work on reserved HTTP characters.
While query string parameters allow you to work around reserved characters by double escaping them or URL encoding them, it is impossible to do so in path parameters since they only operate with characters reserved in the HTTP protocol. If a variable value in the path parameter features new or more of the reserved character, it breaks the path and generates a malformed request.
When Should You Use Path Parameters?
While the path and query parameters differ in many ways, they both have their boons.
However, both styles should conform to the HTTP protocol for them to work. And since path parameters offer a more descriptive and distinct style, are more readable and easier to understand, they are the ideal choice when you want to identify a specific resource.