Upgrade to Pro — share decks privately, control downloads, hide ads and more …

How JSON-API Can Bring Sanity to Your PHP APIs

How JSON-API Can Bring Sanity to Your PHP APIs

Presented at NomadPHP, September 2015: https://www.youtube.com/watch?v=qSDfrITkvjo

APIs are everywhere: many return JSON and are RESTful or even provide hypermedia controls, but chances are they do not adhere to any standard. Essentially they all speak a different language that has to be learned for each specific provider. Wouldn’t it be great if there was a sane specification that lets you standardize your API? Something around which the community can build tools so you don’t have to reinvent the wheel over and over again? In this talk I will introduce the JSON-API specification and explain how it can benefit you on your next API project.

Henning Glatter-Götz

September 18, 2015
Tweet

More Decks by Henning Glatter-Götz

Other Decks in Programming

Transcript

  1. COVERED BY JSON-API SPEC Content Negotiation Document Structure Fetching Data

    Creating, Updating and Deleting Resources Query Parameters Errors
  2. SINGLE RESOURCE { "data": { "type": "articles", "id": "1", "attributes":

    { "title": "Hello world", "body": "bla bla bla" } } }
  3. SINGLE RESOURCE WITH RELATIONSHIP { "data": { "type": "articles", "id":

    "1", "attributes": { "title": "Hello world", "body": "bla bla bla" }, "relationships": { "author": { "links": { "self": "http://example.com/articles/1/relationships/author", "related": "http://example.com/articles/1/author" }, "data": { "type": "people", "id": "9" } } } }, "included": [] }
  4. ERRORS HTTP/1.1 422 Unprocessable Entity Content-Type: application/vnd.api+json { "errors": [

    { "status": "422", "source": { "pointer": "/data/attributes/first-name" }, "title": "Invalid Attribute", "detail": "First name must contain at least three characters." } ] }
  5. PHP SERVER LIBRARIES * GOintegro/HATEOAS - Symfony 2 /Doctrine 2

    * tobscure/json-api * neomerx/json-api - framework agnostic * neomerx/limoncello-collins Laravel-based quick start server * lode/jsonapi * woohoolabs/yin * nilportugues/json-api * nilportugues/symfony2-jsonapi-transformer - Symfony 2 * nilportugues/laravel5-jsonapi-transformer - Laravel 5
  6. HAND CRAFTED // Lots of hand written code here //

    : // to manually build array representation of document structure return json_encode($data);
  7. NEOMERX/JSON-API 01 $encoder = Encoder::instance([ 02 ArticleModel::class => ArticleSchema::class 03

    AuthorModel::class => AuthorSchema::class 04 ], 05 new EncoderOptions($encodeOptions, 'http://example.com') 06 ); 07 08 return $encoder->encodeData($articles);