All Projects → tobyzerner → Json Api Php

tobyzerner / Json Api Php

Licence: mit
JSON-API (http://jsonapi.org) responses in PHP.

Projects that are alternatives of or similar to Json Api Php

Api
姬长信API For Docker 一个基于多种编程语言开源免费不限制提供生活常用,出行服务,开发工具,金融服务,通讯服务和公益大数据的平台.
Stars: ✭ 743 (+74.41%)
Mutual labels:  api, json-api, json
Laravel5 Jsonapi
Laravel 5 JSON API Transformer Package
Stars: ✭ 313 (-26.53%)
Mutual labels:  api, json-api, json
Jsonapi parameters
Rails-way to consume JSON:API input
Stars: ✭ 50 (-88.26%)
Mutual labels:  api, json-api, json
Element Api
Create a JSON API/Feed for your elements in Craft.
Stars: ✭ 493 (+15.73%)
Mutual labels:  api, json-api, json
Polr
🚡 A modern, powerful, and robust URL shortener
Stars: ✭ 4,147 (+873.47%)
Mutual labels:  api, json-api, json
Json Api Dart
JSON:API client for Dart/Flutter
Stars: ✭ 53 (-87.56%)
Mutual labels:  api, json-api, json
Dictfier
Python library to convert/serialize class instances(Objects) both flat and nested into a dictionary data structure. It's very useful in converting Python Objects into JSON format
Stars: ✭ 67 (-84.27%)
Mutual labels:  api, json-api, json
Rki Covid Api
🦠🇩🇪📈 An API for the spread of covid-19 in Germany. Data from Robert-Koch-Institut.
Stars: ✭ 98 (-77%)
Mutual labels:  api, json-api, json
Jsonapi Utils
Build JSON API-compliant APIs on Rails with no (or less) learning curve.
Stars: ✭ 191 (-55.16%)
Mutual labels:  api, json-api, json
Symfony Jsonapi
JSON API Transformer Bundle for Symfony 2 and Symfony 3
Stars: ✭ 114 (-73.24%)
Mutual labels:  api, json-api, json
Datoji
A tiny JSON storage service. Create, Read, Update, Delete and Search JSON data.
Stars: ✭ 222 (-47.89%)
Mutual labels:  api, json-api, json
Jsonapi Rb
Efficiently produce and consume JSON API documents.
Stars: ✭ 219 (-48.59%)
Mutual labels:  api, json-api, json
Jsonapi Rails
Rails gem for fast jsonapi-compliant APIs.
Stars: ✭ 242 (-43.19%)
Mutual labels:  api, json-api, json
Restful Doom
HTTP+JSON API hosted inside the 1993 DOOM engine!
Stars: ✭ 263 (-38.26%)
Mutual labels:  api, json
Php Curl Class
PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs
Stars: ✭ 2,903 (+581.46%)
Mutual labels:  api, json
Spine
A Swift library for working with JSON:API APIs. It supports mapping to custom model classes, fetching, advanced querying, linking and persisting.
Stars: ✭ 267 (-37.32%)
Mutual labels:  json-api, json
Toapi
Every web site provides APIs.
Stars: ✭ 3,209 (+653.29%)
Mutual labels:  api, json
Safrs
SqlAlchemy Flask-Restful Swagger Json:API OpenAPI
Stars: ✭ 255 (-40.14%)
Mutual labels:  json-api, json
Mojojson
A simple and fast JSON parser.
Stars: ✭ 271 (-36.38%)
Mutual labels:  json-api, json
Fractalistic
A framework agnostic, developer friendly wrapper around Fractal
Stars: ✭ 309 (-27.46%)
Mutual labels:  api, json

PHP JSON-API

Build Status Coverage Status Quality Score Pre Release License

JSON-API responses in PHP.

Works with version 1.0 of the spec.

⚠️ The project is no longer maintained. Check out tobyzerner/json-api-server instead.

Install

via Composer:

composer require tobscure/json-api

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

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

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

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

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 & 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

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

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

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

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

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

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

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

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

Running Tests

$ phpunit

License

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].