Sunday, June 19, 2016

JSON API Advanced source Usage

Advanced source Usage

In the example below, the user is sending an invalid JSON API request, because it’s missing the data member:
PATCH /posts/1 HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{ "datum": [ ] }
Therefore, the server responds:
HTTP/1.1 422 Unprocesssable Entity
Content-Type: application/vnd.api+json

{
  "errors": [
    {
      "source": { "pointer": "" },
      "detail":  "Missing `data` Member at document's top level."
    }
  ]
}
It uses source to point to the top-level of the document (""). (Pointing to “/” would be an appropriate reference to the string "some value" in the request document {"": "some value"}. Pointing to "/data" would be invalid because the request document did not have a value at "/data", and source is always given with reference to the request document.)
If the server cannot parse the request as valid JSON, including source doesn’t make sense (because there’s no JSON document for source to refer to). Here’s how the server might respond to an invalid JSON document:
{
  "errors": [{
    "status": "400",
    "detail": "JSON parse error - Expecting property name at line 1 column 2 (char 1)."
  }]
}

Invalid Query Parameters

The source member can also be used to indicate that the error originated from a problem with a URI query parameter, like so:
GET /api/posts/1?include=auther HTTP/1.1
HTTP/1.1 400 Bad Request
Content-Type: application/vnd.api+json

{
  "errors": [
    {
      "source": { "parameter": "include" },
      "title":  "Invalid Query Parameter",
      "detail": "The resource does not have an `auther` relationship path."
    }
  ]
}
In most cases, JSON API requires the server to return an error when it encounters an invalid value for a JSON API–defined query parameter. However, for API-specific query parameters (i.e. those not defined by JSON API), a server may choose to ignore an invalid parameter and have the request succeed, rather than respond with an error. API-specific query parameters must contain one non a-z character.
Other examples of invalid parameters include: ?felds[people]= (invalid parameter name; should be fields[people]) and ?redirect_to=http%3A%2F%2Fwww.owasp.org (invalid parameter, in this case, a phishing attack), etc.

No comments: