PHPackages                             alsvanzelf/jsonapi - 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. alsvanzelf/jsonapi

ActiveLibrary[API Development](/categories/api)

alsvanzelf/jsonapi
==================

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

v3.0.0(4mo ago)54150.0k—0.5%10[3 issues](https://github.com/lode/jsonapi/issues)[1 PRs](https://github.com/lode/jsonapi/pulls)4MITPHPPHP &gt;=8.2CI failing

Since Jun 9Pushed 3mo ago2 watchersCompare

[ Source](https://github.com/lode/jsonapi)[ Packagist](https://packagist.org/packages/alsvanzelf/jsonapi)[ Docs](https://github.com/lode/jsonapi)[ RSS](/packages/alsvanzelf-jsonapi/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (31)Used By (4)

jsonapi
=======

[](#jsonapi)

A simple and human-friendly library for api servers (php serving json).

It allows you to generate json output according to the [JSON:API v1.1](https://jsonapi.org/) standard, while being easy to understand for people without knowledge of the jsonapi standard.

The JSON:API standard makes it easy for clients to fetch multiple resources in one call and understand the relations between them. Read more about it at [jsonapi.org](https://jsonapi.org/).

The library's code uses strict typing and is checked against a high standard in phpstan and rector. It is tested extensively with 99% coverage.

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

[](#installation)

[Use Composer](http://getcomposer.org/) require to get the latest stable version:

```
composer require alsvanzelf/jsonapi

```

The library requires php 8.2. Use the latest [v2.x release](/releases/tag/v2.5.0) for lower php versions.

#### Upgrading from v1 or v2

[](#upgrading-from-v1-or-v2)

If you used v1 or v2 of this library, see [UPGRADE\_1\_TO\_2.md](/UPGRADE_1_TO_2.md) or [UPGRADE\_2\_TO\_3.md](/UPGRADE_1_TO_2.md) on how to upgrade.

Getting started
---------------

[](#getting-started)

#### A small resource example

[](#a-small-resource-example)

```
use alsvanzelf\jsonapi\ResourceDocument;

$document = new ResourceDocument(type: 'user', id: 42);
$document->add('name', 'Zaphod Beeblebrox');
$document->add('heads', 2);
$document->sendResponse();
```

Which will result in:

```
{
	"jsonapi": {
		"version": "1.1"
	},
	"data": {
		"type": "user",
		"id": "42",
		"attributes": {
			"name": "Zaphod Beeblebrox",
			"heads": 2
		}
	}
}
```

#### A collection of resources with relationships

[](#a-collection-of-resources-with-relationships)

```
use alsvanzelf\jsonapi\CollectionDocument;
use alsvanzelf\jsonapi\objects\ResourceObject;

$arthur      = new ResourceObject('user', 1);
$ford        = new ResourceObject('user', 2);
$zaphod      = new ResourceObject('user', 42);
$heartOfGold = new ResourceObject('starship', 2001);

$arthur->add('name', 'Arthur Dent');
$ford->add('name', 'Ford Prefect');
$zaphod->add('name', 'Zaphod Beeblebrox');
$heartOfGold->add('name', 'Heart of Gold');

$zaphod->addRelationship('drives', $heartOfGold);

$users    = [$arthur, $ford, $zaphod];
$document = CollectionDocument::fromResources(...$users);
$document->sendResponse();
```

Which will result in:

```
{
	"jsonapi": {
		"version": "1.1"
	},
	"data": [
		{
			"type": "user",
			"id": "1",
			"attributes": {
				"name": "Arthur Dent"
			}
		},
		{
			"type": "user",
			"id": "2",
			"attributes": {
				"name": "Ford Prefect"
			}
		},
		{
			"type": "user",
			"id": "42",
			"attributes": {
				"name": "Zaphod Beeblebrox"
			},
			"relationships": {
				"drives": {
					"data": {
						"type": "starship",
						"id": "2001"
					}
				}
			}
		}
	],
	"included": [
		{
			"type": "starship",
			"id": "2001",
			"attributes": {
				"name": "Heart of Gold"
			}
		}
	]
}
```

#### Turning an exception into jsonapi

[](#turning-an-exception-into-jsonapi)

```
use alsvanzelf\jsonapi\ErrorsDocument;

$exception = new Exception('That is not valid', 422);

$document = ErrorsDocument::fromException($exception);
$document->sendResponse();
```

Which will result in:

```
{
	"jsonapi": {
		"version": "1.1"
	},
	"errors": [
		{
			"status": "422",
			"code": "Exception",
			"meta": {
				"class": "Exception",
				"message": "That is not valid",
				"code": 422,
				"file": "README.md",
				"line": 137,
				"trace": []
			}
		}
	]
}
```

This can be useful for development. For production usage, you can better construct an `ErrorsDocument` with only specific values.

#### Using extensions and profiles

[](#using-extensions-and-profiles)

The [Atomic Operations extension](https://jsonapi.org/ext/atomic/) and the [Cursor Pagination profile](https://jsonapi.org/profiles/ethanresnick/cursor-pagination/) come packaged along. Any 3rd party of self-made extension can be applied with:

```
use alsvanzelf\jsonapi\ResourceDocument;
use alsvanzelf\jsonapi\interfaces\ExtensionInterface;

class ExampleExtension implements ExtensionInterface {
	public function getOfficialLink(): string {
		return 'https://example.org/extension-documentation';
	}

	public function getNamespace(): string {
		return 'foo';
	}
}

$document = new ResourceDocument('user', 42);
$document->add('name', 'Zaphod Beeblebrox');

$extension = new ExampleExtension();
$document->applyExtension($extension);
$document->addExtensionMember($extension, 'bar', 'baz');

$document->sendResponse();
```

Which will result in:

```
{
    "foo:bar": "baz",
    "jsonapi": {
        "version": "1.1",
        "ext": [
            "https://example.org/extension-documentation"
        ]
    },
    "data": {
        "type": "user",
        "id": "42",
        "attributes": {
            "name": "Zaphod Beeblebrox"
        }
    }
}
```

A similar flow can be used for profiles.

#### Other examples

[](#other-examples)

Examples for all kind of responses are in the [/examples](/examples) directory.

Features
--------

[](#features)

This library supports [v1.1 of the JSON:API specification](https://jsonapi.org/format/1.1/).

It has support for generating &amp; sending documents with:

- single resources
- resource collections
- to-one and to-many relationships
- errors (easily turning exceptions into jsonapi output)
- v1.1 extensions and profiles
- v1.1 @-members for JSON-LD and others

Also there's tools to help processing of incoming requests:

- parse request options (include paths, sparse fieldsets, sort fields, pagination, filtering)
- parse request documents for creating, updating and deleting resources and relationships

Next to custom extensions/profiles, the following [official extensions/profiles](https://jsonapi.org/extensions/) are included:

- Atomic Operations extension ([example code](/examples/atomic_operations_extension.php), [specification](https://jsonapi.org/ext/atomic/))
- Cursor Pagination profile ([example code](/examples/cursor_pagination_profile.php), [specification](https://jsonapi.org/profiles/ethanresnick/cursor-pagination/))

Plans for the future include:

- validate request options ([\#58](https://github.com/lode/jsonapi/issues/58))
- validate request documents ([\#57](https://github.com/lode/jsonapi/issues/57))

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

[](#contributing)

If you use the library, please ask questions or share what can be improved by [creating an issue](https://github.com/lode/jsonapi/issues).

For bugs [issues](https://github.com/lode/jsonapi/issues) or [Pull Requests](https://github.com/lode/jsonapi/pulls) are welcome!

See [/script's README](/script) to steps to setup a local development environment.

Licence
-------

[](#licence)

[MIT](/LICENSE)

###  Health Score

62

—

FairBetter than 99% of packages

Maintenance77

Regular maintenance activity

Popularity46

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity86

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 98.8% 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 ~143 days

Recently: every ~10 days

Total

28

Last Release

132d ago

Major Versions

v1.5.1 → v2.0.0-beta2019-02-17

v2.5.0 → v3.0.0-beta2026-01-05

PHP version history (3 changes)v1.0.0PHP &gt;=5.4

v2.0.0-betaPHP &gt;=5.6

v3.0.0-betaPHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/bfe07388f3ca4b0ac7725bc717893340bd7f168e44dd7ae64ee3d58874e16fde?d=identicon)[lode](/maintainers/lode)

---

Top Contributors

[![lode](https://avatars.githubusercontent.com/u/511245?v=4)](https://github.com/lode "lode (595 commits)")[![jasperwissels](https://avatars.githubusercontent.com/u/9079288?v=4)](https://github.com/jasperwissels "jasperwissels (3 commits)")[![kat3su](https://avatars.githubusercontent.com/u/2160182?v=4)](https://github.com/kat3su "kat3su (3 commits)")[![Pierozi](https://avatars.githubusercontent.com/u/5133487?v=4)](https://github.com/Pierozi "Pierozi (1 commits)")

---

Tags

api-serverjsonjson-apijsonapiphpjsonapijsonapiJSON-API

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/alsvanzelf-jsonapi/health.svg)

```
[![Health](https://phpackages.com/badges/alsvanzelf-jsonapi/health.svg)](https://phpackages.com/packages/alsvanzelf-jsonapi)
```

###  Alternatives

[neomerx/json-api

Framework agnostic JSON API (jsonapi.org) implementation

7373.6M27](/packages/neomerx-json-api)[cloudcreativity/laravel-json-api

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

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

PHPUnit test helpers to check JSON API documents.

141.6M3](/packages/cloudcreativity-json-api-testing)[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)

PHPackages © 2026

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