Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Api Rest Utils Laravel Package

everycheck/api-rest-utils

A Symfony utility package offering a JSON response builder with common API statuses and custom headers, plus a paginated repository trait for filtering, ordering, and searching entities across joins.

View on GitHub
Deep Wiki
Context7

api-rest-utils

Some basic utils we use in every api rest project under symfony

Response builder

For now there is one class responsible for building different kind of response needed by an api rest.

All methode return a Symfony\Component\HttpFoundation\Response, with json content.

usage

    public function getAction($id)
    {
        $response  = new ResponseBuilder($this->get('jms_serializer'));
        $entity = $this->getDoctrine()->getManager()->getRepository(Entity::class)->find($id);
        
        if(empty($entity)) return $response->notFound();
        
        return $response->ok($entities);
    }

Response available

  • json
  • empty
  • notFound
  • ok
  • created
  • deleted
  • conflict
  • forbiddenRoute
  • forbiddenAcl
  • forbidden
  • badRequest
  • formError for parsing symfony form error
  • unauthorized

Configuring headers

Use the addHeaders method :

    public function getAction($id)
    {
        $response  = new ResponseBuilder($this->get('jms_serializer'));
        $entity = $this->getDoctrine()->getManager()->getRepository(Entity::class)->find($id);
        
        if(empty($entity)) return $response->notFound();
        
        return $response->addHeaders('X-something','some-value')->ok($entities);
    }

Find paginated with filter and order by

Another common thing required is a find all entity matching certain filter and ordered by some criteria

Just add the trait in your repository like this :

<?php

namespace ACMEBundle\Repository;

use EveryCheck\ApiRest\Utils\PaginatedRepositoryTrait;

class PostRepository extends \Doctrine\ORM\EntityRepository
{
    use PaginatedRepositoryTrait;

    const BASE_QUERY_NAME = 'post';

    const LEFT_JOIN_ALIAS_LIST = [
        'post.author'          => 'author',
        'post.responses'        => 'response',
    ];

    const FILTER_OPTION = [
        ['filterOn'=>'author.username'   , 'filterName' => 'username'         , 'filterKind'=>'like'         ],
        ['filterOn'=>'response.message'  , 'filterName' => 'response_message' , 'filterKind'=>'like'         ],
        ['filterOn'=>'response.date'     , 'filterName' => 'date'             , 'filterKind'=>'greaterThan'  ],
    ];

}

Here an exaple where you enable search on 3 fields on left join. You can also order by those fields.

Controler side :

    /**
     * @Route("/posts", name="get_post_list", methods={"GET"})
     */
    public function getPostListAction(Request $request)
    {       
        $posts = $this->getEntityManager()->getRepository(Post::class)->findPaginatedFromRequest($request);
        return $this->getResponseBuilder()->ok($posts);
    }

Response example :

{
    "limit": 10,
    "offset": 0,
    "count": 1,
    "entities": [
        {
            "message":"something",
            "author":{
                "username":"someone"
            },
            "responses":[
                {
                    "message":"something else",
                    "author":{
                        "username":"someone_else"
                    }
                }
            ]
        }
    ]
}

Easy ?

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route