Developed with love by KnpLabs Hire us for your project!
65

jsonapi-bundle

by paknahad

the fastest way to generate API based on jsonapi.org using woohoolabs/yin

Latest Stable Version
Build Status
License: MIT
Total Downloads

JsonApiBundle For Symfony

JsonApiBundle is a Symfony bundle. It is the fastest way to generate API based on JsonApi
using woohoolabs/yin Library.

Installing

  1. Install symfony

    composer create-project symfony/skeleton YOUR_PROJECT

  2. Install the maker bundle

    composer require symfony/maker-bundle phootwork/collection --dev

  3. Install the bundle

    composer require paknahad/jsonapi-bundle

    For Symfony 4 use:

    composer require paknahad/jsonapi-bundle:3.0.0

  4. Add below line to config/bundles.php

    Paknahad\JsonApiBundle\JsonApiBundle::class => ['all' => true],

Usage

  1. Use below command to generate entities one by one:

    bin/console make:entity

    for example, Book and Author entity is as follows:
    ```php
    class Book
    {
    /**
    * @ORM\Id()
    * @ORM\GeneratedValue()
    * @ORM\Column(type="integer")
    */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;
    
    /**
     * @ORM\Column(type="string", length=20, nullable=true)
     */
    private $isbn;
    
    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Author", inversedBy="books")
     */
    private $authors;
    
    ... 
    
    ```php
    class Author
    {
        /**
         * @ORM\Id()
         * @ORM\GeneratedValue()
         * @ORM\Column(type="integer")
         */
        private $id;
    
        /**
         * @ORM\Column(type="string", length=255)
         * @Assert\NotBlank()
         * @Assert\Length(min=3)
         */
        private $name;
    
        /**
         * @ORM\ManyToMany(targetEntity="App\Entity\Book", mappedBy="authors")
         */
        private $books;
    
        ...
    
  2. Generate CRUD API:

    bin/console make:api

  3. You can find the generated "collections" for postman and swagger in the following path and then test the API:

    collection/postman.json
    collection/swagger.yaml

Features

Pagination

http://example.com/books?page[number]=5&page[size]=30

Sorting

  • Ascending on name field: http://example.com/books?sort=name
  • Decending on name field: http://example.com/books?sort=-name
  • Multiple fields: http://example.com/books?sort=city,-name
  • Field on a relation: http://example.com/books?sort=author.name

Relationships

http://example.com/books?include=authors

multiple relationships

http://example.com/books?include=authors.phones,publishers

Search

As the JSON API specification does not specify exactly how filtering should work different methods of
filtering can be used. Each method is supplied with a Finder service. Each registered Finder will be able to append
conditions to the search query. If you register multiple Finders they are all active at the same time. This enables
your API to support multiple filtering methods.

Basic Finder.

A basic Finder is included in this library offering simple filtering capabilities:

This request will return all the books that author's name begin with hamid

http://example.com/books?filter[authors.name]=hamid%

Below line has additional condition: books which have "php" in their title.

http://example.com/books?filter[title]=%php%&filter[authors.name]=hamid%

Setting a default filter on the IndexAction

By using $resourceCollection->getQuery() you can get access on the query object.
use "r" alias for referring to the current entity. in this example the "r" refers to the "ProjectEntity"
```php
class ProjectController extends Controller
{
/**
* @Route("/", name="projects_index", methods="GET")
*/
public function index(ProjectRepository $projectRepository, ResourceCollection $resourceCollection): ResponseInterface
{
$resourceCollection->setRepository($projectRepository);

    $resourceCollection->getQuery()->where('r.user_id = :s1')->setParameter(...);
    $resourceCollection->handleIndexRequest();

    return $this->jsonApi()->respond()->ok(
        new ProjectsDocument(new ProjectResourceTransformer()),
        $resourceCollection
    );
}

#### Other Finders
Currently the following Finders are available via other bundles:

- [mnugter/jsonapi-rql-finder-bundle][7] - [RQL][8] based Finder

- [paknahad-jsonapi-querifier-bundle][10] - [Querifier][11] based Finder

#### Creating a custom Finder
A Finder can be registered via a service tag in the services definition. The tag `paknahad.json_api.finder` must be
added to the service for the Finder to be resigered.

Example:

```

Each Finder must implement the Paknahad\JsonApiBundle\Helper\Filter\FinderInterface interface.

Validation

Error on validating associations
json
{
"jsonapi": {
"version": "1.0"
},
"errors": [
{
"detail": "Invalid value for this relation",
"source": {
"pointer": "/data/relationships/authors",
"parameter": "1"
}
}
]
}

Validate attributes if you have defined validators on entities.
json
{
"jsonapi": {
"version": "1.0"
},
"errors": [
{
"detail": "This value is too short. It should have 3 characters or more.",
"source": {
"pointer": "/data/attributes/name",
"parameter": "h"
}
}
]
}

Error handler

All errors such as:
- Internal server error (500)
- Not found (404)
- Access denied (403)

has responses like this:
json
{
"meta": {
"code": 0,
"message": "No route found for \"GET /book\"",
"file": "/var/www/vendor/symfony/http-kernel/EventListener/RouterListener.php",
"line": 139,
"trace": [
{
"file": "/var/www/vendor/symfony/event-dispatcher/EventDispatcher.php",
"line": 212,
"function": "onKernelRequest"
},
{
"file": "/var/www/vendor/symfony/event-dispatcher/EventDispatcher.php",
"line": 44,
"function": "doDispatch"
},
{
"file": "/var/www/vendor/symfony/http-kernel/HttpKernel.php",
"line": 125,
"function": "dispatch"
},
{
"file": "/var/www/vendor/symfony/http-kernel/HttpKernel.php",
"line": 66,
"function": "handleRaw"
},
{
"file": "/var/www/vendor/symfony/http-kernel/Kernel.php",
"line": 188,
"function": "handle"
},
{
"file": "/var/www/public/index.php",
"line": 37,
"function": "handle"
}
]
},
"links": {
"self": "/book"
},
"errors": [
{
"status": "404",
"code": "NO_ROUTE_FOUND_FOR_\"GET_/BOOK\"",
"title": "No route found for \"GET /book\""
}
]
}

NOTICE: the "meta" field gets filled just on development environment.

The MIT License (MIT)

Copyright (c) 2018 Hamid Paknahad

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
  • replace depricated Inflector class by new one
    By paknahad, 1 month ago
  • Add status from exception code
    By paknahad, 4 months ago
  • fix coding style
    By paknahad, 4 months ago
  • Add support for showing meta fields when APP_DEBUG var is set to true
    By paknahad, 4 months ago
  • add an ability to set default filters. fix #52
    By paknahad, 5 months ago
  • fix coding style.
    By paknahad, 5 months ago
  • Fix sorting by deep relationships
    By paknahad, 5 months ago
  • Add phpunit cache file to .gitignore
    By paknahad, 5 months ago
  • add openapi documentation schema with configuration
    By paknahad, 5 months ago
  • Update readme
    By paknahad, 6 months ago
  • Undo file permissions
    By paknahad, 6 months ago
  • Fix coding style
    By paknahad, 6 months ago
  • Upgrade dependencies
    By paknahad, 6 months ago
  • fix dev dependency
    By paknahad, 6 months ago
  • Add symfony 5 support
    By paknahad, 6 months ago
  • Typo in AbstractEntityHydrator.tpl.php
    By paknahad, 9 months ago
  • fix return type of "getJsonApi" in jsonapi_documents.
    By paknahad, 11 months ago
  • Merge branch 'V2.2'
    By paknahad, 11 months ago
  • Add value transformer on validation error. fix #42
    By paknahad, 11 months ago
  • fix coding style of ValidatorTrait.
    By paknahad, 11 months ago
  • Update the tests.
    By paknahad, 11 months ago
  • fix the errors which reported by phpstan.
    By paknahad, 11 months ago
  • Add and configure the phpstan.
    By paknahad, 11 months ago
  • Add a validator for relations.
    By paknahad, 11 months ago
  • Refactor the ErrorHandler.
    By paknahad, 11 months ago
  • fix a typo.
    By paknahad, 11 months ago
  • Add a link for reaching to every document.
    By paknahad, 11 months ago
  • Omit the relations of entity when not included.
    By paknahad, 11 months ago
  • Replace the "ClassMetadata" by "ClassMetadataInfo"
    By paknahad, 11 months ago
  • upgrade the yin to version 4.
    By paknahad, 1 year ago