MBuhot MBuhot - 1 month ago 5
reST (reStructuredText) Question

Should links in json-api responses be encoded?

Should the query params in links appearing in JSON-API responses be percent-encoded?

The examples from jsonapi.org are not encoded, as in:

{
"links": {
"self": "http://example.com/articles",
"next": "http://example.com/articles?page[offset]=2",
"last": "http://example.com/articles?page[offset]=10"
},
"data": [{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON API paints my bikeshed!"
}
]
}


However, there is also a note regarding encoding parameters in requests:

GET /articles?include=author&fields[articles]=title,body&fields[people]=name HTTP/1.1
Accept: application/vnd.api+json



Note: The above example URI shows unencoded [ and ] characters simply for readability. In practice, these characters must be percent-encoded, per the requirements in RFC 3986.


Does this note apply only to requests? Or should responses also be percent-encoded, as in:

{
"links": {
"self": "http://example.com/articles",
"next": "http://example.com/articles?page%5Boffset%5D=2",
"last": "http://example.com/articles?page%5Boffset%5D=10"
},
"data": [{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON API paints my bikeshed!"
}
]
}

Ray Ray
Answer

Yes, the note about encoding URI's in your question applies only to the request, not the response

With a json string returned inside a response, the only thing required to escape is the double quote character "

GET requests (not responses) are a different ball of wax. Anything in a GET request passed as a parameter in the URL must be URL encoded. So if you have a parameter url=http://some.url.com, the url on the right of the parameter assignment needs encoding.

It's tricky with POST and PUT requests. Depending on the content type set in the header you may need to encode. If your content type is application/json, you should not need to url encode anyting in your json string, (excluding the before mentioned ").

Now, if the specificed content encoding you state doesn't match what your sending (or if you didn't explicitly add one and it defaults to something), like if you send content-type: application/x-www-form-urlencoded but send a json string, the API service may or may not accept it and who know what how it will treat the content inside as far a url decoding it.

Comments