Skip to content

Parsing API Parameters

Lucian Daniliuc edited this page Oct 21, 2022 · 9 revisions

Additionally to encoding capabilities the library provides a few more helpful classes for

  • Parsing HTTP query parameters.
  • Parsing HTTP headers from input requests.
  • Preparing HTTP responses.

Query Parameters

Application may use the following parameters in URL

The package provides parser for includes, field sets and sorts in BaseQueryParser class. Parsing for pagination and filtering is not provided for the reason it is not defined by JSON API specification. However class BaseQueryParser is designed to be used as a base class for such parsers/validator and provides a few helpful methods for that.

Please be aware of that the result of the BaseQueryParser::getIncludes method could not be used as parameter for the Encoder::withIncludedPaths method. The method is build to use along with a query builder to generate the needed data. To use both methods together follow this example:

function iterableKeys(iterable $iterable): iterable {
    foreach ($iterable as $key => $value) {
        yield $key;
    }
}
$json = Encoder::instance([/* needed parameter */])
 ->withIncludedPaths(iterableKeys($parser->getIncludes()))
 ->encodeData($comments);;

Header Parameters (Accept and Content-Type)

Clients have certain negotiation responsibilities for Content-Type and Accept HTTP headers. Which means JSON API server must handle those headers in accordance with RFC 2616.

That's an example of a header that servers must support

Accept: application/vnd.api+json;q=0.5,text/html;q=0.8;*/*;q=0.1

The server may choose to support text/html in order to simplify viewing content via a web browser.

Clients send their preferences in Accept and Content-Type headers. The library parses headers in accordance with RFC 7231.

Sample usage below

use Neomerx\JsonApi\Contracts\Http\Headers\AcceptHeaderInterface;
use Neomerx\JsonApi\Factories\Factory;
use Neomerx\JsonApi\Http\Headers\AcceptHeader;

$parser = new HeaderParametersParser(new Factory());

$acceptValue = 'foo/bar.baz;media=param;q=0.5;ext="ext1,ext2", type/*, */*';
foreach($parser->parseAcceptHeader($acceptValue) as $acceptMediaType) {
    ...
}

$contentTypeValue = 'application/vnd.api+json';
$contentMediaType = $parser->parseContentTypeHeader($contentTypeValue);

HTTP Responses

BaseResponses

JSON API has a variety of possible HTTP responses. The package provides \Neomerx\JsonApi\Http\BaseResponses class which encapsulates those requirements and designed to be used as a base class.

Integration sample

// `Responses` should extend `Neomerx\JsonApi\Http\BaseResponses`
$responses = new Responses(...);

// response for newly created resource with
// HTTP code 201 + 'location' header
$response = $responses->getCreatedResponse($newAuthor);