PHPackages                             juliangut/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. juliangut/json-api

ActiveLibrary[API Development](/categories/api)

juliangut/json-api
==================

PSR7 aware json-api integration

12.2k[3 issues](https://github.com/juliangut/json-api/issues)[2 PRs](https://github.com/juliangut/json-api/pulls)PHP

Since Mar 7Pushed 1y ago1 watchersCompare

[ Source](https://github.com/juliangut/json-api)[ Packagist](https://packagist.org/packages/juliangut/json-api)[ RSS](/packages/juliangut-json-api/feed)WikiDiscussions master Synced yesterday

READMEChangelogDependenciesVersions (3)Used By (0)

[![PHP version](https://camo.githubusercontent.com/6913801024bb6087176dec5fdb59388730a49b167cbb013222a7acbaecb48b7c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e302d3838393242462e7376673f7374796c653d666c61742d737175617265)](http://php.net)[![Latest Version](https://camo.githubusercontent.com/901b7c1edab71b42d3aee33600e98ebeb4f09836a5c05b7fd3963216379a0216/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a756c69616e6775742f6a736f6e2d6170692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/juliangut/json-api)[![License](https://camo.githubusercontent.com/4dcc7aa709af6c6b939f928e27fc9b934f300a27d36cf21bd0eb6f85a9010b32/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6a756c69616e6775742f6a736f6e2d6170692e7376673f7374796c653d666c61742d737175617265)](https://github.com/juliangut/json-api/blob/master/LICENSE)

[![Total Downloads](https://camo.githubusercontent.com/85c906680ba1d0346926536ec4729336c0c852828f5a614ef8f5fc8fa799d373/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a756c69616e6775742f6a736f6e2d6170692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/juliangut/json-api/stats)[![Monthly Downloads](https://camo.githubusercontent.com/649f0382a54b2b6dab0d97c28c6e6f48f4fc0fa2bf833d69f4eeca63662e5bc7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6a756c69616e6775742f6a736f6e2d6170692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/juliangut/json-api/stats)

json-api
========

[](#json-api)

Easy JSON:API integration.

Installation
------------

[](#installation)

### Composer

[](#composer)

```
composer require juliangut/json-api

```

symfony/yaml to parse yaml files

```
composer require symfony/yaml

```

Usage
-----

[](#usage)

Require composer autoload file

```
require './vendor/autoload.php';
```

```
use Jgut\JsonApi\Manager;
use Jgut\JsonApi\Configuration;
use Neomerx\JsonApi\Schema\Error;

$configuration = new Configuration([
    'sources' => ['/path/to/resource/files'],
]);

$jsonApiManager = new Manager($configuration);

// Get encoded errors
$jsonApiManager->encodeErrors(new Error());

// Get encoded resources
$jsonApiManager->encodeResources(new MyClass(), new ServerRequestInstance());
```

### Configuration

[](#configuration)

- `sources` must be an array containing arrays of configurations to create MappingDriver objects:
    - `type` one of \\Jgut\\JsonApi\\Mapping\\Driver\\DriverFactory constants: `DRIVER_ATTRIBUTE`, `DRIVER_PHP`, `DRIVER_JSON`, `DRIVER_XML`, `DRIVER_YAML` or `DRIVER_ANNOTATION` **if no driver, defaults to DRIVER\_ATTRIBUTE**
    - `path` a string path or array of paths to where mapping files are located (files or directories) **REQUIRED if no driver**
    - `driver` an already created \\Jgut\\JsonApi\\Mapping\\Driver\\DriverInterface object **REQUIRED if no type AND path**
- `attributeName` name of the PSR-7 Request attribute that will hold query parameters for resource encoding, defaults to 'JSON\_API\_query\_parameters'
- `schema` class name implementing \\Jgut\\JsonApi\\Schema\\MetadataSchemaInterface (\\Jgut\\JsonApi\\Schema\\MetadataSchema by default)
- `prefix` prefix for generated URLs
- `metadataResolver` an instance of \\Jgut\\Mapping\\Metadata\\MetadataResolver. It is highly recommended to provide a PSR-16 cache to metadata resolver on production
- `encodingOptions` global encoding options, an instance of \\Jgut\\JsonApi\\Encoding\\OptionsInterface
- `jsonApiVersion` none by default
- `jsonApiMeta` optional global metadata

Middleware
----------

[](#middleware)

Use PSR-15 middleware `Jgut\JsonApi\Middleware\JsonApiMiddleware` in order to validate request being a valid JSON:API specification request

```
use Jgut\JsonApi\Manager;
use Jgut\JsonApi\Middleware\JsonApiMiddleware;
use Psr\Http\Message\ResponseFactoryInterface;

/** @var ResponseFactoryInterface $responseFactory */
/** @var Manager $jsonApiManager */

$middleware = new JsonApiMiddleware($responseFactory, $jsonApiManager);

// Add the middleware to any PSR-15 compatible library/framework, such as Slim, Mezzio, etc
```

Console command
---------------

[](#console-command)

```
use Symfony\Component\Console\Application;
use Jgut\Slim\PHPDI\Command\ListCommand;

/** @var \Slim\App $app */
$container = $app->getContainer();

$cli = new Application('Slim CLI');
$cli->add(new ListCommand($container));

$app->run();
```

### List container definitions

[](#list-container-definitions)

List defined container definitions supporting searching

Resource mapping
----------------

[](#resource-mapping)

Resources can be defined in two basic ways: by writing them down in definition files of various types or directly defined in attributes on classes

### Attributes

[](#attributes)

#### ResourceObject (Class level)

[](#resourceobject-class-level)

Identifies each JSON:API resource. Its presence is mandatory in each resource class

Accepts an optional "name" that overrides default (class name with lowercase first letter)

```
use Jgut\JsonApi\Mapping\Attribute\ResourceObject;
use Jgut\JsonApi\Mapping\Attribute\ResourcePrefix;
use Jgut\JsonApi\Mapping\Attribute\ResourceSchema;

#[ResourceObject(
    name: 'company',
    prefix: 'resourcePrefix',
    schema: 'customSchemaClass',
    meta: ['meta1' => 'value'],
)]
class Company
{
}
```

- `name`, optional, resource name, lowercase first letter class name by default
- `prefix`, optional, resource url prefix when links are included
- `schema`, optional, class name implementing \\Jgut\\JsonApi\\Schema\\MetadataSchemaInterface. Override default one

#### Identifier (Property level)

[](#identifier-property-level)

The resource identifier

```
use Jgut\JsonApi\Mapping\Attribute\Getter;
use Jgut\JsonApi\Mapping\Attribute\Identifier;
use Jgut\JsonApi\Mapping\Attribute\ResourceObject;
use Jgut\JsonApi\Mapping\Attribute\Setter;

#[ResourceObject]
class Owner
{
    #[Identifier(
        name: 'identifier',
        getter: 'getIdentifier',
        setter: 'setIdentifier',
        meta: ['meta1' => 'value'],
    )]
    protected string $id;
}
```

- `name`, optional, identifier name, lowercase first letter property name by default
- `getter`, optional, method in the class that gives access to the property. By default, uppercase first letter property name prefixed by "is" for booleans or "get" for the rest of types
- `setter`, optional, method in the class that sets the value for the property, uppercase first letter property name prefixed by "set"
- `meta`, optional, list of optional array/value array of identifier metadata

#### Attribute (Property level)

[](#attribute-property-level)

A resource attribute

```
use Jgut\JsonApi\Mapping\Attribute\Attribute;
use Jgut\JsonApi\Mapping\Attribute\Getter;
use Jgut\JsonApi\Mapping\Attribute\ResourceObject;
use Jgut\JsonApi\Mapping\Attribute\Setter;

#[ResourceObject]
class Company
{
    #[Attribute(
        name: 'title',
        getter: 'getTitle',
        setter: 'setTitle',
        groups: ['view'],
    )]
    protected string $title;
}
```

- `name`, optional, attribute name, lowercase first letter property name by default
- `getter`, optional, method in the class that gives access to the property. By default, uppercase first letter property name prefixed by "is" for booleans or "get" for the rest of types
- `setter`, optional, method in the class that sets the value for the property, uppercase first letter property name prefixed by "set"
- `groups`, optional, array of groups to which the attribute belongs

#### Relationship (Property level)

[](#relationship-property-level)

A resource relationship

```
use Jgut\JsonApi\Mapping\Attribute\Relationship;
use Jgut\JsonApi\Mapping\Attribute\ResourceObject;

#[ResourceObject]
class Company
{
    #[Relationship(
        name: 'owner',
        getter: 'getOwner',
        setter: 'setOwner',
        groups: ['view'],
    )]
    protected Owner $companyOwner;
}
```

- `name`, optional, relationship name, lowercase first letter property name by default
- `getter`, optional, method in the class that gives access to the property. By default, uppercase first letter property name prefixed by "is" for booleans or "get" for the rest of types
- `setter`, optional, method in the class that sets the value for the property, uppercase first letter property name prefixed by "set"
- `groups`, optional, array of groups to which the relationship belongs

#### Links

[](#links)

```
use Jgut\JsonApi\Mapping\Attribute\Link;
use Jgut\JsonApi\Mapping\Attribute\LinkRelated;
use Jgut\JsonApi\Mapping\Attribute\LinkSelf;
use Jgut\JsonApi\Mapping\Attribute\ResourceObject;
use Jgut\JsonApi\Mapping\Attribute\Relationship;

#[ResourceObject]
#[LinkSelf(false)]
#[LinkRelated]
#[Link(
    href: 'http://...',
    title: 'example',
    meta: ['meta1' => 'value'],
)]
class Company
{
    #[Relationship]
    #[LinkSelf]
    #[LinkRelated(false)]
    #[Link(
        href: 'http://...',
        title: 'example',
        meta: ['meta1' => 'value'],
    )]
    protected Owner $companyOwner;
}
```

##### LinkSelf (Class level)

[](#linkself-class-level)

Determines whether self link is included in the response

##### LinkRelated (Class level)

[](#linkrelated-class-level)

Determines whether self link is included in the response when the resource is included as a relationship

##### Link (Class and Property level)

[](#link-class-and-property-level)

Adds as many custom link to the resource or field as needed

- `href`, required, href of the link
- `title`, optional, link title
- `meta`, optional, list of optional link metadata (see metadata section below)

#### Metadata

[](#metadata)

```
use Jgut\JsonApi\Mapping\Attribute\Attribute;
use Jgut\JsonApi\Mapping\Attribute\Meta;
use Jgut\JsonApi\Mapping\Attribute\Relationship;
use Jgut\JsonApi\Mapping\Attribute\ResourceObject;

#[ResourceObject]
#[Meta(key: 'meta1', value: 'value')]
class Company
{
    #[Identifier]
    #[Meta(key: 'meta2', value: 'value')]
    protected string $id;

    #[Relationship]
    #[Meta(key: 'meta3', value: 'value')]
    #[Meta(key: 'meta4', value: 'value')]
    protected Owner $owner;
}
```

There are two kinds of metadata:

##### Meta Attribute (Class and Property level)

[](#meta-attribute-class-and-property-level)

Assign one or more metadata to a resource, identifier or relationship

- `key`, required, metadata key
- `value`, required, metadata value

##### Other metadata

[](#other-metadata)

Link attributes accept metadata as a key/value array

### Definition files

[](#definition-files)

##### PHP

[](#php)

```
return [
    [
        'class' => 'CompanyClass',
        'name' => 'company',
        'prefix' => 'company',
        'schema' => 'MetadataCompanySchemaClass',
        'linkSelf' => true,
        'linkRelated' => false,
        'meta' => [
            'meta1' => 'value',
        ],
        'identifier' => [
            'property' => 'uuid',
            'name' => 'id',
            'getter' => 'getUuid',
            'setter' => 'setUuid',
            'meta' => [
                'meta2' => 'value',
            ]
        ],
        'attributes' => [
            [
                'property' => 'email',
                'name' => 'email',
                'getter' => 'getEmail',
                'setter' => 'setEmail',
            ],
        ],
        'relationships' => [
            [
                'class' => 'OwnerClass',
                'property' => 'owner',
                'name' => 'owner',
                'linkSelf' => true,
                'linkRelated' => true,
                'links' => [
                    'example' => [
                        'href' => 'http://example.com',
                        'meta' => [
                            'meta3' => 'value',
                        ],
                    ],
                ],
                'meta' => [
                    'meta4' => 'value',
                ],
            ],
        ],
    ],
];
```

##### JSON

[](#json)

```
[
  {
    "class": "CompanyClass",
    "name": "company",
    "prefix": "company",
    "schema": "MetadataCompanySchemaClass",
    "linkSelf": true,
    "linkRelated": false,
    "meta": {
      "meta1": "value"
    },
    "identifier": {
      "property": "uuid",
      "name": "id",
      "getter": "getUuid",
      "setter": "setUuid",
      "meta": {
        "meta2": "value"
      }
    },
    "attributes": [
      {
        "property": "email",
        "name": "email",
        "getter": "getEmail",
        "setter": "setEmail"
      }
    ],
    "relationships": [
      {
        "class": "OwnerClass",
        "property": "owner",
        "name": "owner",
        "linkSelf": true,
        "linkRelated": true,
        "links": {
          "example": {
            "href": "http://example.com",
            "meta": {
              "meta3": "value"
            }
          }
        },
        "meta": {
          "meta4": "value"
        }
      }
    ]
  }
]
```

##### XML

[](#xml)

```

      value

        value

              value

          value

```

##### YAML

[](#yaml)

```
- class: "CompanyClass"
  name: "company"
  prefix: "company"
  schema: "MetadataCompanySchemaClass"
  linkSelf: true
  linkRelated: false
  meta:
    meta1: "value"
  identifier:
    property": "uuid"
    name: "id"
    getter: "getUuid"
    setter: "setUuid"
    meta:
      meta2: "value"
  attributes:
    - property: "email"
      name: "email"
      getter: "getEmail"
      setter: "setEmail"
  relationships:
    - class: "OwnerClass"
      property: "owner"
      name: "owner"
      linkSelf: true
      linkRelated: true
      links:
        example:
          href: "http://example.com"
          meta:
            meta3: "value"
      meta:
        meta4: "value"
```

### Annotations

[](#annotations)

**Annotations are deprecated and will be removed eventually. Use Attribute mapping when possible**.

You need to require Doctrine's annotation package

```
composer require doctrine/annotations

```

#### ResourceObject (Class level)

[](#resourceobject-class-level-1)

Identifies each resource. Its presence is mandatory on each resource class

```
use Jgut\JsonApi\Mapping\Annotation as JJM;

/**
 * @JJM\ResourceObject(
 *     name="company",
 *     schema="CustomSchemaClass",
 *     prefix="resourcePrefix",
 *     linkSelf=true,
 *     linkRelated=false,
 *     links={"link1": "http://...", "link2": "http://..."},
 *     meta={"meta1" => "value", "meta2" => "value"}
 * )
 */
class Company
{
}
```

- `name`, optional, resource name, lowercase first letter class name by default
- `prefix`, optional, resource url prefix when links are included
- `schema`, optional, class name implementing \\Jgut\\JsonApi\\Schema\\MetadataSchemaInterface. Override default one
- `linkSelf`, optional bool, display self link, null by default
- `linkRelated`, optional bool, display self link when included, null by default
- `links`, optional, list of optional key/value array of resource links
- `meta`, optional, list of optional array/value array of resource metadata

#### Identifier (Property level)

[](#identifier-property-level-1)

The resource identifier

```
use Jgut\JsonApi\Mapping\Annotation as JJM;

/**
 * @JJM\ResourceObject
 */
class Owner
{
    /**
     * @JJM\Identifier(
     *     name="id",
     *     getter="getId",
     *     setter="setId",
     *     meta={"meta1" => "value", "meta2" => "value"}
     * )
     */
    protected $id;
}
```

- `name`, optional, identifier name, lowercase first letter property name by default
- `getter`, optional, method in the class that gives access to the property. By default, uppercase first letter property name prefixed by "is" for booleans or "get" for the rest of types
- `setter`, optional, method in the class that sets the value for the property, uppercase first letter property name prefixed by "set"
- `meta`, optional, list of optional array/value array of identifier metadata

#### Attribute (Property level)

[](#attribute-property-level-1)

Defines each and every attribute accessible on the resource

```
use Jgut\JsonApi\Mapping\Annotation as JJM;

/**
 * @JJM\ResourceObject
 */
class Company
{
    /**
     * @JJM\Attribute(
     *     name="email",
     *     getter="getEmail",
     *     setter="setEmail",
     *     groups={"view"}
     * )
     */
    protected string $email;
}
```

- `name`, optional, attribute name, lowercase first letter property name by default
- `getter`, optional, method in the class that gives access to the property. By default, uppercase first letter property name prefixed by "is" for booleans or "get" for the rest of types
- `setter`, optional, method in the class that sets the value for the property, uppercase first letter property name prefixed by "set"
- `groups`, optional, array of groups to which the attribute belongs

#### Relationship (Property level)

[](#relationship-property-level-1)

Identifies this resource relationships

```
use Jgut\JsonApi\Mapping\Annotation as JJM;

/**
 * @JJM\ResourceObject
 */
class Company
{
    /**
     * @JJM\Relationship(
     *     name="company",
     *     getter="getCompany",
     *     setter="setCompany",
     *     groups=["view"]
     *     linkSelf=true,
     *     linkRelated=false,
     *     links={"link1": "http://...", "link2": "http://..."],
     *     meta={"meta1" => ·"value", "meta2" => "value"}
     * )
     */
    protected Owner $company;
}
```

- `name`, optional, relationship name, lowercase first letter property name by default
- `getter`, optional, method in the class that gives access to the property. By default, uppercase first letter property name prefixed by "is" for booleans or "get" for the rest of types
- `setter`, optional, method in the class that sets the value for the property, uppercase first letter property name prefixed by "set"
- `groups`, optional, array of groups to which the relationship belongs
- `linkSelf`, optional bool, display self link, null by default
- `linkRelated`, optional bool, display self link when included, null by default
- `links`, optional, list of optional key/value array of resource links
- `meta`, optional, list of optional array/value array of relationship metadata

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

[](#contributing)

Found a bug or have a feature request? [Please open a new issue](https://github.com/juliangut/json-api/issues). Have a look at existing issues before.

See file [CONTRIBUTING.md](https://github.com/juliangut/json-api/blob/master/CONTRIBUTING.md)

License
-------

[](#license)

See file [LICENSE](https://github.com/juliangut/json-api/blob/master/LICENSE) included with the source code for a copy of the license terms.

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance6

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity23

Early-stage or recently created project

 Bus Factor1

Top contributor holds 97.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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/4c50421f1ab4148354dc2dd5dcaba168656b17ea913b310d112deb39a6f73ca1?d=identicon)[juliangut](/maintainers/juliangut)

---

Top Contributors

[![juliangut](https://avatars.githubusercontent.com/u/1104131?v=4)](https://github.com/juliangut "juliangut (74 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

jsonjson-apipsr15psr7psr7-middleware

### Embed Badge

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

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

###  Alternatives

[exsyst/swagger

A php library to manipulate Swagger specifications

35816.3M7](/packages/exsyst-swagger)[hubspot/api-client

Hubspot API client

24015.5M18](/packages/hubspot-api-client)[pocketmine/bedrock-protocol

An implementation of the Minecraft: Bedrock Edition protocol in PHP

172437.8k11](/packages/pocketmine-bedrock-protocol)[botman/driver-telegram

Telegram driver for BotMan

94452.6k6](/packages/botman-driver-telegram)

PHPackages © 2026

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