URL matrix parameters vs. query parameters
Asked Answered
M

3

203

I'm wondering whether to use matrix or query parameters in my URLs. I found an older discussion to that topic not satisfying.

Examples

At first sight matrix params seem to have only advantages:

  • more readable
  • no encoding and decoding of "&" in XML documents is required
  • URLs with "?" are not cached in many cases; URLs with matrix params are cached
  • matrix parameters can appear everywhere in the path and are not limited to its end
  • matrix parameters can have more than one value: paramA=val1,val2

But there are also disadvantages:

  • only a few frameworks like JAX-RS support matrix parameters
  • When a browser submits a form via GET, the params become query params. So it ends up in two kinds of parameters for the same task. To not confuse users of the REST services and limit the effort for the developers of the services, it would be easier to use always query params - in this area.

Since the developer of the service can choose a framework with matrix param support, the only remaining disadvantage would be that browsers create by default query parameters.

Are there any other disadvantages? What would you do?

Mojave answered 12/1, 2010 at 10:14 Comment(5)
I'm not sure what the big deal is with matrix URLs. According to the w3c design article that TBL wrote, it was just a design idea and explicitly states that it's not a feature of the web. Things like relative URLs aren't implemented when using it. If you want to use it, that's fine; there's just no standard way to use it because it's not a standard.Comitative
@Steve Pomeroy: Is this the article you mention: w3.org/DesignIssues/MatrixURIs.htmlSwaddle
@Marcel: yup. For those thinking about matrix URLs, note the "Status: personal view" at the top of the document.Comitative
can matrix params have more than one value? really?Anitraaniweta
query params can have muliple values too: some.where/thing?paramA=1&paramA=6542Flyblow
I
237

The important difference is that matrix parameters apply to a particular path element while query parameters apply to the request as a whole. This comes into play when making a complex REST-style query to multiple levels of resources and sub-resources:

http://example.com/res/categories;name=foo/objects;name=green/?page=1

It really comes down to namespacing.

Note: The 'levels' of resources here are categories and objects.

If only query parameters were used for a multi-level URL, you would end up with

http://example.com/res?categories_name=foo&objects_name=green&page=1

This way you would also lose the clarity added by the locality of the parameters within the request. In addition, when using a framework like JAX-RS, all the query parameters would show up within each resource handler, leading to potential conflicts and confusion.

If your query has only one "level", then the difference is not really important and the two types of parameters are effectively interchangeable, however, query parameters are generally better supported and more widely recognized. In general, I would recommend that you stick with query parameters for things like HTML forms and simple, single-level HTTP APIs.

Indebtedness answered 9/4, 2011 at 3:25 Comment(3)
irrelavant: does /? part representing a resource?Aluin
The ? starts the query parameter part of the request. Query parameters are the most common type of URL parameters, as opposed to matrix parameters. The slash before the question mark makes sure that the query parameter page doesn't run into the matrix parameter that precedes the slash. I suppose if there were no matrix parameters attached to categories, the query parameters could attached without the slash like this: http://example.com/res/categories?page=1Spiegel
While it's true that the matrix parameters may be specified in any path segment, JAX-RS for example does not associate them with the path segment they were appended to when injecting with @MatrixParam. According to "Restful Java with JAX-RS 2.0", a request like "GET /mercedes/e55;color=black/2006/interior;color=tan" would have an ambiguous definition of the color matrix param. Although it looks like if you process each PathSegment individually you can figure it out... So useful but more work to get to it than if you specified categoryName=foo;objectName=green.Supine
N
24

In addition to Tim Sylvester's answer I would like to provide an example of how matrix parameters can be handled with JAX-RS .

  1. Matrix parameters at the last resource element

    http://localhost:8080/res/categories/objects;name=green
    

    You can access them using the @MatrixParam annotation

    @GET
    @Path("categories/objects")
    public String objects(@MatrixParam("name") String objectName) {
      return objectName;
    }
    

    Response

    green
    

    But like the Javadoc states

    Note that the @MatrixParam annotation value refers to a name of a matrix parameter that resides in the last matched path segment of the Path-annotated Java structure that injects the value of the matrix parameter.

    ... what brings us to point 2

  2. Matrix parameters in the middle of an URL

    http://localhost:8080/res/categories;name=foo/objects;name=green
    

    You can access matrix parameters anywhere using path variables and @PathParam PathSegment.

    @GET
    @Path("{categoryVar:categories}/objects")
    public String objectsByCategory(@PathParam("categoryVar") PathSegment categorySegment, 
                                    @MatrixParam("name") String objectName) {
      MultivaluedMap<String, String> matrixParameters = categorySegment.getMatrixParameters();
      String categorySegmentPath = categorySegment.getPath();
      String string = String.format("object %s, path:%s, matrixParams:%s%n", objectName,
              categorySegmentPath, matrixParameters);
      return string;
    }
    

    Response

    object green, path:categories, matrixParams:[name=foo]
    

    Since the matrix parameters are provided as a MultivaluedMap you can access each by

    List<String> names = matrixParameters.get("name");
    

    or if you only need the first one

    String name = matrixParameters.getFirst("name");
    
  3. Get all matrix parameters as one method parameter

    http://localhost:8080/res/categories;name=foo/objects;name=green//attributes;name=size
    

    Use a List<PathSegment> to get them all

    @GET
    @Path("all/{var:.+}")
    public String allSegments(@PathParam("var") List<PathSegment> pathSegments) {
      StringBuilder sb =  new StringBuilder();
    
      for (PathSegment pathSegment : pathSegments) {
        sb.append("path: ");
        sb.append(pathSegment.getPath());
        sb.append(", matrix parameters ");
        sb.append(pathSegment.getMatrixParameters());
        sb.append("<br/>");
      }
    
      return sb.toString();
    }
    

    Response

    path: categories, matrix parameters [name=foo]
    path: objects, matrix parameters [name=green]
    path: attributes, matrix parameters [name=size]
    
Nadinenadir answered 25/1, 2018 at 7:43 Comment(0)
K
11

--Too important to be relegated to comment section.--

I'm not sure what the big deal is with matrix URLs. According to the w3c design article that TBL wrote, it was just a design idea and explicitly states that it's not a feature of the web. Things like relative URLs aren't implemented when using it. If you want to use it, that's fine; there's just no standard way to use it because it's not a standard.

Steve Pomeroy.

So short answer is, if you need RS for business purpose, you are better off using request parameter.

Koestler answered 7/9, 2015 at 15:39 Comment(7)
Someone tell that to Angular 2 developers who decided they were so unique they needed to implement this instead!Mixon
@MattPileggi Angular2 guys are the reason I am reading this thread. I mean why deal with something that probably adds not much value to an already existing well know way of doing stuff!Eclecticism
@MattPileggi I am also reading this because of Angular 2. Almost every aspect of Angular 2 is highly specialized, unconventional, and at odds with existing usage patterns. It is as of yet unproven that this adds mitigating value.Straightout
So guys, i'm here for the same reason too, but let me add some points to this discution with this issue about url matrix and google analytis on angular 2 team github page: github.com/angular/angular/issues/11740 But after some research about it, url matrix notation appears be more human-readable than url query parameters, mainly when we need of some parameter in the middle or url (not only in the end of it).Dudley
I guess everyone who thinks this is non-standard isn't familiar with the uri template spec either? Encoding complex objects in path params is a very useful feature of uri templates; just because most people don't know about or use it doesn't mean it's some evil conspiracy by angular devs to inject useless complexity into your life.Valentin
Pffft - "<thing I didn't know existed until now> is non-standard thus preserving the acceptability of my ignorance". What TBL did or didn't decide to do with an idea is largely immaterial. It was not a feature of his web in 2001. The features of the web are whatever the client and server implementers choose them to be. If Angular supports matrix params and JAX-RS supports them and these are you chosen implementation tools then go ahead and use what works.Rarefaction
It was not the kind of thing on which you could rely in 1996: w3.org/DesignIssues/MatrixURIs.html However, it's no longer true, you can find some references about it in some W3C documents about WADL: w3.org/Submission/wadlCredence

© 2022 - 2024 — McMap. All rights reserved.