JSON:API serializer for PHP resources

Related tags

API kwai-jsonapi
Overview

kwai-jsonapi

Latest Stable Version PHP Version Require

A JSON:API serializer for PHP classes using PHP attributes.

Currently, this library has no support for links.

Installation

composer require kwai/jsonapi

Requirements

PHP attributes are used to serialize a PHP class to a JSONAPI resource. So, the PHP version must be at least 8.0. There are no other external dependencies.

Documentation

#[JSONAPI/Resource]

The "JSONAPI/Resource" attribute is used to set the type of the resource.

  • The type argument is required.
  • This attribute can only be applied to a class.
  • By default, the id is retrieved from the id property. Use the id argument to use a method or a property with another name.
use Kwai\JSONAPI;

#[JSONAPI/Resource(type: 'people')]
class Person 
{
    public function __construct(
        // We need at least an id property.
        private string $id,
    )
}

#[JSONAPI/Attribute]

The "JSONAPI/Attribute" attribute is used to set an attribute of a resource.

  • This attribute can be applied to a property or a method of a class.
  • The name argument can be used to give a name to the property.
  • When applied to a method, the name argument is required.
use Kwai\JSONAPI;

#[JSONAPI/Resource(type: 'people')]
class Person 
{
    public function __construct(
        private string $id,
        #[JSONAPI/Attribute]
        private string $name,
        private int $age,
    ) {
    }
    
    #[JSONAPI/Attribute(name: 'age')]
    public function getAge(): int
    {
        return $this->age;
    }
}

Properties may be private. A method must be public.

With a Person instance like this:

$person = new Person(
    id: '1',
    name: 'Jigoro Kano',
    age: 77,
);

The result will be:

{
  "data": {
    "type": "people",
    "id": "1",
    "attributes": {
      "name": "Jigoro Kano",
      "age": 77
    }
  }
}

#[JSONAPI/Relationship]

The "JSONAPI/Relationship" is used to map a relationship.

  • This attribute can be applied to a property or a method.
  • The name argument can be used to give a name to the relationship.
  • When no name argument is set for a property, the name of the property will be used.
  • When applied to a method, the name argument is required.
#[JSONAPI\Resource(type:'athletes')]
class Athlete
{
    public function __construct(
        private string $id,
        #[JSONAPI\Attribute]
        private string $name,
        #[JSONAPI\Relationship]
        private Country $country,
    ) {
    }
}

Properties may be private. A method must be public.

The linked resource must contain a JSONAPI\Resource attribute. If not, a JSONAPI\Exception will be thrown. A relationship can also be an array.

With the given PHP code:

$country = new Country(
    id: '1',
    code: 'BEL',
);
$athlete = new Athlete(
    id: '1',
    name: 'Ingrid Berghmans',
    country: $country
)

The result of the serializing will be:

{
  "data": {
    "type": "athletes",
    "id": "1",
    "attributes": {
      "name": "Ingrid Berghmans"
    },
    "relationships": {
      "country": {
        "data": {
          "type": "countries",
          "id": "1"
        }
      }
    }
  },
  "included": [
    {
      "type": "countries",
      "id": "1",
      "attributes": {
        "code": "BEL"
      }
    }
  ]
}

Serializing

The JSONAPI\Document class is used to serialize an object or an array to a JSON:API structure.

use Kwai\JSONAPI;

$person = new Person(
    id: '1',
    name: 'Jigoro Kano',
    age: 77,
);

try {
    $jsonapi = JSONAPI\Document::createFromObject($person)->serialize();
    // Send $jsonapi to the client...
} catch (JSONAPI\Exception $e) {
    // An exception occurred while serializing the PHP object.
}

Meta

Meta information can be set with the setMeta method.

    try {
        $jsonapi =
            JSONAPI\Document::createFromObject($person)
                ->setMeta('count', 1)
                ->serialize();
    } catch (JSONAPI\Exception $e) {
        // Handle exception...
    }
You might also like...
Read and write OpenAPI 3.0.x YAML and JSON files and make the content accessible in PHP objects.

php-openapi Read and write OpenAPI 3.0.x YAML and JSON files and make the content accessible in PHP objects. It also provides a CLI tool for validatin

pedre-response is a standard structure of json response

PedreResponse It's very important to use same structure for responses in large projects that PedreResponse package can do it for you. PedreResponse is

A robust JSON decoder/encoder with support for schema validation.

A robust wrapper for json_encode()/json_decode() that normalizes their behavior across PHP versions, throws meaningful exceptions and supports schema validation by default.

Like FormRequests, but for validating against a json-schema

JSON Schema Request Laravels Form Request Validation for JSON Schema documents Installation composer require wt-health/laravel-json-schema-request Us

微信支付 API v3 的 PHP Library,同时也支持 API v2

微信支付 WeChatPay OpenAPI SDK [A]Sync Chainable WeChatPay v2&v3's OpenAPI SDK for PHP 概览 微信支付 APIv2&APIv3 的Guzzle HttpClient封装组合, APIv2已内置请求数据签名及XML转换器,应

Simple PHP API client for tube-hosting.com rest API

Tube-Hosting API PHP client Explanation This PHP library is a simple api wrapper/client for the tube-hosting.com api. It is based on the provided docu

Chargebee API PHP Client (for API version 2 and Product Catalog version 2.0)

chargebee-php-sdk Overview This package provides an API client for Chargebee subscription management services. It connects to Chargebee REST APIs for

API documentation API SCB EASY APP

SCB-API-EASY V3.0 API documentation SIAM COMMERCIAL BANK PUBLIC COMPANY LTD. API SCB Easy V3 endpoint = https://fasteasy.scbeasy.link 1.0. Get balance

Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota & International
Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota & International

Courier API Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota (dalam negeri) & International

Comments
  • Add PHP 8.0 and 8.1 test

    Add PHP 8.0 and 8.1 test

    Changed log

    • Since this PHP package requires php-8.0 version at least, I think the php-8.1 version should be tested, too.
    • Install shivammathur/setup-php@v2 to complete above issue.
    • Letting this repository on master branch trigger GitHub Action when pushing the commit.
    • Letting this repository on any branch name trigger GitHub Action when creating the PR.
    • This GitHub Action building log is available here.
    opened by peter279k 0
Releases(1.0.2)
Owner
Franky Braem
develops software in C/C++,PHP,Java,Perl,Python, Javascript ... for more than 30 years.
Franky Braem
This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science courses and the like.

Simple PHP API v.1.0 This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science courses a

Edson M. de Souza 14 Nov 18, 2021
This API provides functionality for creating and maintaining users to control a simple To-Do-List application. The following shows the API structure for users and tasks resources.

PHP API TO-DO-LIST v.2.0 This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science cours

Edson M. de Souza 6 Oct 13, 2022
Best resources restful api for developers

Best resources restful api for developers (with JSON:API standar specification design).

Noval 2 Jan 18, 2022
The efficient and elegant JSON:API 1.1 server library for PHP

Woohoo Labs. Yin Woohoo Labs. Yin is a PHP framework which helps you to build beautifully crafted JSON:APIs. Table of Contents Introduction Features W

Woohoo Labs. 237 Nov 28, 2022
The efficient and elegant, PSR-7 compliant JSON:API 1.1 client library for PHP

Woohoo Labs. Yang Woohoo Labs. Yang is a PHP framework which helps you to communicate with JSON:API servers more easily. Table of Contents Introductio

Woohoo Labs. 160 Oct 16, 2022
Laravel API 文档生成器,可以将基于 Laravel 项目的项目代码,自动生成 json 或 md 格式的描述文件。

Thresh Laravel API 文档生成器,可以将基于 Laravel 项目的项目代码,自动生成 json 或 md 格式的描述文件。 安装 $ composer require telstatic/thresh -vvv 功能 生成 Markdown 文档 生成 Postman 配置文件 生

静止 5 Jul 12, 2021
JSON API (jsonapi.org) package for Laravel applications.

cloudcreativity/laravel-json-api Status This package has now been rewritten, substantially improved and released as the laravel-json-api/laravel packa

Cloud Creativity 753 Dec 28, 2022
Simple and effective multi-format Web API Server to host your PHP API as Pragmatic REST and / or RESTful API

Luracast Restler ![Gitter](https://badges.gitter.im/Join Chat.svg) Version 3.0 Release Candidate 5 Restler is a simple and effective multi-format Web

Luracast 1.4k Dec 14, 2022
Quickly and easily expose Doctrine entities as REST resource endpoints with the use of simple configuration with annotations, yaml, json or a PHP array.

Drest Dress up doctrine entities and expose them as REST resources This library allows you to quickly annotate your doctrine entities into restful res

Lee Davis 88 Nov 5, 2022
PHP implementation of JSON schema. Fork of the http://jsonschemaphpv.sourceforge.net/ project

JSON Schema for PHP A PHP Implementation for validating JSON Structures against a given Schema with support for Schemas of Draft-3 or Draft-4. Feature

Justin Rainbow 3.4k Dec 26, 2022