Search code examples
jsonapiresthal-json

Parametarized links in HAL json


Assuming I have an endpoint GET /api/foos/{id} which has optional parameters: includes, query, type should I create a link for each of the 'usecases' or can I include it as a single link?

Should it look more like this:

"_links":{
   "self": { "href": "/api/foos/1" },
   "includes": { "href": "/api/foos/1{?includes}", "templated": true },
   "query": { "href": "/api/foos/1{?query}", "templated": true },
   "type": { "href": "/api/foos/1{?type}", "templated": true },
}

Or maybe like this:

"_links":{
   "self": { "href": "/api/foos/1" },
   "query": { "href": "/api/foos/1{?includes}{?query}{?type}", "templated": true },
}

What if I also have paging related links, like next, prev etc. Should I include these templates for them, too? For example:

"next": { "href": "/api/foos?page=2{?includes}", "templated": true }

Solution

  • According to RFC6570, Section 3.2.1 (which is the foundation for URL templating) you can add multiple parameters and parameter without a value will be ignored:

    A variable that is undefined (Section 2.3) has no value and is ignored by the expansion process.

    That means for your example that you can use following HAL response:

    "_links":{
       "self": { "href": "/api/foos/1" },
       "query": { "href": "/api/foos/1{?includes,query,type}", "templated": true },
    }
    

    And it should work for your paging example as well.