PHPackages                             bavix/json-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. bavix/json-api

AbandonedArchivedLibrary[API Development](/categories/api)

bavix/json-api
==============

JSON-API responses in PHP

1.1.0(5y ago)316.2kMITPHPPHP ^7.0|^8.0

Since Aug 7Pushed 5y agoCompare

[ Source](https://github.com/bavix/json-api)[ Packagist](https://packagist.org/packages/bavix/json-api)[ RSS](/packages/bavix-json-api/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (3)Dependencies (1)Versions (12)Used By (0)

PHP JSON-API
============

[](#php-json-api)

[![Build Status](https://camo.githubusercontent.com/368b53e8d2f0b72d21a46830c97543bbe129b2107dbfb70916e229fe01274a73/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f62617669782f6a736f6e2d6170692f6d61737465722e7376673f7374796c653d666c6174)](https://travis-ci.org/bavix/json-api)[![Coverage Status](https://camo.githubusercontent.com/b774c3a76f9df821376a30c82010cdddd136c1608ad7e3c10337cf13d2350310/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f62617669782f6a736f6e2d6170692e7376673f7374796c653d666c6174)](https://scrutinizer-ci.com/g/bavix/json-api/code-structure)[![Quality Score](https://camo.githubusercontent.com/582bfee1c028368193ed89a0c352d797715869c7929e70d6c06a8ad08a3427b4/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f62617669782f6a736f6e2d6170692e7376673f7374796c653d666c6174)](https://scrutinizer-ci.com/g/bavix/json-api)[![Pre Release](https://camo.githubusercontent.com/d03320d3438d19027b4c3d7f63a4e3c8f2f43e35bedd8b04f3afd5d14ac94164/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f767072652f62617669782f6a736f6e2d6170692e7376673f7374796c653d666c6174)](https://github.com/bavix/json-api/releases)[![License](https://camo.githubusercontent.com/9ca8c94b87e6f79cee585a0a9d0afcfe3baee71db1cbdc35e03f8b7dad9209f7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f62617669782f6a736f6e2d6170692e7376673f7374796c653d666c6174)](https://packagist.org/packages/bavix/json-api)

[JSON-API](http://jsonapi.org) responses in PHP.

Works with version 1.0 of the spec.

Install
-------

[](#install)

via Composer:

```
composer require bavix/json-api
```

Usage
-----

[](#usage)

```
use Tobscure\JsonApi\Document;
use Tobscure\JsonApi\Collection;

// Create a new collection of posts, and specify relationships to be included.
$collection = (new Collection($posts, new PostSerializer))
    ->with(['author', 'comments']);

// Create a new JSON-API document with that collection as the data.
$document = new Document($collection);

// Add metadata and links.
$document->addMeta('total', count($posts));
$document->addLink('self', 'http://example.com/api/posts');

// Output the document as JSON.
echo json_encode($document);
```

### Elements

[](#elements)

The JSON-API spec describes *resource objects* as objects containing information about a single resource, and *collection objects* as objects containing information about many resources. In this package:

- `Tobscure\JsonApi\Resource` represents a *resource object*
- `Tobscure\JsonApi\Collection` represents a *collection object*

Both Resources and Collections are termed as *Elements*. In conceptually the same way that the JSON-API spec describes, a Resource may have **relationships** with any number of other Elements (Resource for has-one relationships, Collection for has-many). Similarly, a Collection may contain many Resources.

A JSON-API Document may contain one primary Element. The primary Element will be recursively parsed for relationships with other Elements; these Elements will be added to the Document as **included** resources.

#### Sparse Fieldsets

[](#sparse-fieldsets)

You can specify which fields (attributes and relationships) are to be included on an Element using the `fields` method. You must provide a multidimensional array organized by resource type:

```
$collection->fields(['posts' => ['title', 'date']]);
```

### Serializers

[](#serializers)

A Serializer is responsible for building attributes and relationships for a certain resource type. Serializers must implement `Tobscure\JsonApi\SerializerInterface`. An `AbstractSerializer` is provided with some basic functionality. At a minimum, a serializer must specify its **type** and provide a method to transform **attributes**:

```
use Tobscure\JsonApi\AbstractSerializer;

class PostSerializer extends AbstractSerializer
{
    protected $type = 'posts';

    public function getAttributes($post, array $fields = null)
    {
        return [
            'title' => $post->title,
            'body'  => $post->body,
            'date'  => $post->date
        ];
    }
}
```

By default, a Resource object's **id** attribute will be set as the `id` property on the model. A serializer can provide a method to override this:

```
public function getId($post)
{
    return $post->someOtherKey;
}
```

#### Relationships

[](#relationships)

The `AbstractSerializer` allows you to define a public method for each relationship that exists for a resource. A relationship method should return a `Tobscure\JsonApi\Relationship` instance.

```
public function comments($post)
{
    $element = new Collection($post->comments, new CommentSerializer);

    return new Relationship($element);
}
```

By default, the `AbstractSerializer` will convert relationship names from `kebab-case` and `snake_case` into a `camelCase` method name and call that on the serializer. If you wish to customize this behaviour, you may override the `getRelationship` method:

```
public function getRelationship($model, $name)
{
    // resolve Relationship called $name for $model
}
```

### Meta &amp; Links

[](#meta--links)

The `Document`, `Resource`, and `Relationship` classes allow you to add meta information:

```
$document = new Document;
$document->addMeta('key', 'value');
$document->setMeta(['key' => 'value']);
```

They also allow you to add links in a similar way:

```
$resource = new Resource($data, $serializer);
$resource->addLink('self', 'url');
$resource->setLinks(['key' => 'value']);
```

You can also easily add pagination links:

```
$document->addPaginationLinks(
    'url', // The base URL for the links
    [],    // The query params provided in the request
    40,    // The current offset
    20,    // The current limit
    100    // The total number of results
);
```

Serializers can provide links and/or meta data as well:

```
use Tobscure\JsonApi\AbstractSerializer;

class PostSerializer extends AbstractSerializer
{
    // ...

    public function getLinks($post) {
        return ['self' => '/posts/' . $post->id];
    }

    public function getMeta($post) {
        return ['some' => 'metadata for ' . $post->id];
    }
}
```

**Note:** Links and metadata of the resource overrule ones with the same key from the serializer!

### Parameters

[](#parameters)

The `Tobscure\JsonApi\Parameters` class allows you to easily parse and validate query parameters in accordance with the specification.

```
use Tobscure\JsonApi\Parameters;

$parameters = new Parameters($_GET);
```

#### getInclude

[](#getinclude)

Get the relationships requested for inclusion. Provide an array of available relationship paths; if anything else is present, an `InvalidParameterException` will be thrown.

```
// GET /api?include=author,comments
$include = $parameters->getInclude(['author', 'comments', 'comments.author']); // ['author', 'comments']
```

#### getFields

[](#getfields)

Get the fields requested for inclusion, keyed by resource type.

```
// GET /api?fields[articles]=title,body
$fields = $parameters->getFields(); // ['articles' => ['title', 'body']]
```

#### getSort

[](#getsort)

Get the requested sort criteria. Provide an array of available fields that can be sorted by; if anything else is present, an `InvalidParameterException` will be thrown.

```
// GET /api?sort=-created,title
$sort = $parameters->getSort(['title', 'created']); // ['created' => 'desc', 'title' => 'asc']
```

#### getLimit and getOffset

[](#getlimit-and-getoffset)

Get the offset number and the number of resources to display using a page- or offset-based strategy. `getLimit` accepts an optional maximum. If the calculated offset is below zero, an `InvalidParameterException` will be thrown.

```
// GET /api?page[number]=5&page[size]=20
$limit = $parameters->getLimit(100); // 20
$offset = $parameters->getOffset($limit); // 80

// GET /api?page[offset]=20&page[limit]=200
$limit = $parameters->getLimit(100); // 100
$offset = $parameters->getOffset(); // 20
```

### Error Handling

[](#error-handling)

You can transform caught exceptions into JSON-API error documents using the `Tobscure\JsonApi\ErrorHandler` class. You must register the appropriate `Tobscure\JsonApi\Exception\Handler\ExceptionHandlerInterface` instances.

```
try {
    // API handling code
} catch (Exception $e) {
    $errors = new ErrorHandler;

    $errors->registerHandler(new InvalidParameterExceptionHandler);
    $errors->registerHandler(new FallbackExceptionHandler);

    $response = $errors->handle($e);

    $document = new Document;
    $document->setErrors($response->getErrors());

    return new JsonResponse($document, $response->getStatus());
}
```

Contributing
------------

[](#contributing)

Feel free to send pull requests or create issues if you come across problems or have great ideas. Any input is appreciated!

### Running Tests

[](#running-tests)

```
$ phpunit
```

License
-------

[](#license)

This code is published under the [The MIT License](LICENSE). This means you can do almost anything with it, as long as the copyright notice and the accompanying license file is left intact.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor1

Top contributor holds 71.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~225 days

Recently: every ~363 days

Total

10

Last Release

1904d ago

Major Versions

v0.4.1 → v1.0.02019-10-31

PHP version history (5 changes)v0.1.0PHP &gt;=5.4.0

v0.1.1PHP &gt;=5.5.9

v0.4.0PHP ^5.5.9 || ^7.0

v1.0.0PHP ^7.0

1.1.0PHP ^7.0|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/266f28651b740a279e636ef42fadcc7d72941c7a4bf9a29c4fd62c72476f0c0e?d=identicon)[REZ1DENT3](/maintainers/REZ1DENT3)

---

Top Contributors

[![tobyzerner](https://avatars.githubusercontent.com/u/128862?v=4)](https://github.com/tobyzerner "tobyzerner (152 commits)")[![vinkla](https://avatars.githubusercontent.com/u/499192?v=4)](https://github.com/vinkla "vinkla (19 commits)")[![localheinz](https://avatars.githubusercontent.com/u/605483?v=4)](https://github.com/localheinz "localheinz (11 commits)")[![hanneskaeufler](https://avatars.githubusercontent.com/u/68024?v=4)](https://github.com/hanneskaeufler "hanneskaeufler (6 commits)")[![kirkbushell](https://avatars.githubusercontent.com/u/65171?v=4)](https://github.com/kirkbushell "kirkbushell (3 commits)")[![rez1dent3](https://avatars.githubusercontent.com/u/5111255?v=4)](https://github.com/rez1dent3 "rez1dent3 (3 commits)")[![f3ath](https://avatars.githubusercontent.com/u/831399?v=4)](https://github.com/f3ath "f3ath (3 commits)")[![franzliedke](https://avatars.githubusercontent.com/u/249125?v=4)](https://github.com/franzliedke "franzliedke (3 commits)")[![ahsanity](https://avatars.githubusercontent.com/u/88349?v=4)](https://github.com/ahsanity "ahsanity (2 commits)")[![Damith88](https://avatars.githubusercontent.com/u/5088628?v=4)](https://github.com/Damith88 "Damith88 (2 commits)")[![josephmcdermott](https://avatars.githubusercontent.com/u/6955944?v=4)](https://github.com/josephmcdermott "josephmcdermott (2 commits)")[![avoelpel](https://avatars.githubusercontent.com/u/14241284?v=4)](https://github.com/avoelpel "avoelpel (2 commits)")[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (1 commits)")[![Big-Shark](https://avatars.githubusercontent.com/u/646054?v=4)](https://github.com/Big-Shark "Big-Shark (1 commits)")[![burki](https://avatars.githubusercontent.com/u/464455?v=4)](https://github.com/burki "burki (1 commits)")[![abhimanyu003](https://avatars.githubusercontent.com/u/265913?v=4)](https://github.com/abhimanyu003 "abhimanyu003 (1 commits)")[![nubs](https://avatars.githubusercontent.com/u/57673?v=4)](https://github.com/nubs "nubs (1 commits)")

---

Tags

jsonapijsonapistandard

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/bavix-json-api/health.svg)

```
[![Health](https://phpackages.com/badges/bavix-json-api/health.svg)](https://phpackages.com/packages/bavix-json-api)
```

###  Alternatives

[cloudcreativity/laravel-json-api

JSON API (jsonapi.org) support for Laravel applications.

7881.1M5](/packages/cloudcreativity-laravel-json-api)[nilportugues/laravel5-json-api

Laravel 5 JSON API Transformer Package

31232.4k1](/packages/nilportugues-laravel5-json-api)[nilportugues/jsonapi-bundle

Symfony 2 &amp; 3 JSON API Transformer Package

11446.0k](/packages/nilportugues-jsonapi-bundle)[nilportugues/json-api

Serializer transformers outputting valid API responses in JSON, JSON API and HAL+JSON API formats.

70106.2k3](/packages/nilportugues-json-api)[alsvanzelf/jsonapi

Human-friendly library to implement JSON:API without needing to know the specification.

54150.0k5](/packages/alsvanzelf-jsonapi)[cloudcreativity/json-api-testing

PHPUnit test helpers to check JSON API documents.

141.6M3](/packages/cloudcreativity-json-api-testing)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
