Giter Club home page Giter Club logo

cakephp-json-api's Introduction

json-api plugin for CakePHP 5

json:api

This plugin implements neomerx/json-api as a View class for cakephp3.

JSON API is a specification for how a client should request that resources be fetched or modified, and how a server should respond to those requests.

JSON API is designed to minimize both the number of requests and the amount of data transmitted between clients and servers. This efficiency is achieved without compromising readability, flexibility, or discoverability.

JSON API requires use of the JSON API media type (application/vnd.api+json) for exchanging data.

Installation

You can install this plugin into your CakePHP application using composer.

The recommended way to install composer packages is:

composer require phantomwatson/cakephp-json-api:dev-master

Usage

This plugin works by using neomerx/json-api php module at its core, my advice is to read up on the docs before proceeding.

Load the plugin by adding it to your bootstrap.php

Plugin::load('JsonApi');

or activate it using the cake shell

$ bin/cake plugin load JsonApi

Then tell your controller to use the JsonApi view

$this->viewBuilder()->className('JsonApi.JsonApi');

The following view variables can be assigned in your controller

Variable Description
_serialize this holds the actual data to pass to the encoder instance, can be an array of entities, a single entity.
_url the base url of the api endpoint
_entities required A list of entities that are going to be mapped to Schemas
_include an array of hash paths what should be in the included section of the response. [ 'posts.author', 'comments' ]
_fieldsets A hash path of fields should be in the resultset [ 'sites' => ['name'], 'people' => ['first_name'] ]
_meta meta data to add to the document
_links links to add to the document this should be an array of Neomerx\JsonApi\Schema\Link objects.

Example

public function initialize()
{
	$this->viewBuilder()->className('JsonApi.JsonApi');

	$this->set('_entities', [
		'Article',
		'Author'
	]);

	$this->set('_url', Router::url('/api', true));
	$this->set('_meta', ['some' => 'global metadata']);
	$this->set('_links', [ // uses Neomerx\JsonApi\Schema\Link
		Link::FIRST => new Link('/authors?page=1'),
		Link::LAST => new Link('/authors?page=9', [
			'meta' => 'data'
		])
	]);
}

public function index()
{
	$articles = $this->Articles->find()
		->all();

	$this->set(compact('articles'));
	$this->set('_serialize', true);

	// optional parameters
	$this->set('_include', [ 'articles', 'articles.comments' ]);
	$this->set('_fieldsets', [ 'articles' => [ 'title' ] ]);
}

Schemas

Entities assigned in _entities are mapped to the EntitySchema base class. This class extends Neomerx\JsonApi\Schema\SchemaProvider.

It is recommended that you create a schema class for each entity you defined by extending the EntitySchema class. Example: if you have an entity in Model\Entity\Author then create a schema class in View\Schema\AuthorSchema

Think of the Schema class as a template that represents an Entity.

Because of this it is possible access the current view object along with Request and helpers. $this->getView() can be called inside the schema if you need it.

Schema example

Example App\View\Schema\AuthorSchema.php (maps to App\Model\Entity\Author)

<?php
namespace TestApp\View\Schema;

use JsonApi\View\Schema\EntitySchema;

class AuthorSchema extends EntitySchema
{
    public function getId($entity)
    {
        return $entity->get('id');
    }

    public function getAttributes($entity)
    {
        return [
            'title' => $entity->title,
            'body' => $entity->body,
            'published' => $entity->published,
            'helper_link' => $this->Url->build(['action' => 'view']) // view helper
        ];
    }

    public function getRelationships($entity, array $includeRelationships = [])
    {
        return [
            'articles' => [
                self::DATA => $entity->articles
            ]
        ];
    }
}

Request handling and routing

This plugin does not handle this for you but can be easily added to your application using cake's RequestHandler component which has support for the json-api Content-Type.

For instance, if you want to automatically decode incoming json-api (application/vnd.api+json) data you can tell RequestHandler to automaticaly handle it.

$this->RequestHandler->config('inputTypeMap.jsonapi', ['json_decode', true]);

RESTfull routing can also be achieved by creating resource routes.

Router::scope('/api', function($routes) {
	$routes->resources('Articles', function($routes) {
		$routes->resources('Authors');
	});
});

cakephp-json-api's People

Contributors

andrej-griniuk avatar bravo-kernel avatar josbeir avatar phantomwatson avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.