Weave Code
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

Rest Api Bridge Bundle Laravel Package

chancegarcia/rest-api-bridge-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chancegarcia/rest-api-bridge-bundle
    

    Add to config/bundles.php:

    Chance\RestApiBridgeBundle\ChanceRestApiBridgeBundle::class => ['all' => true],
    
  2. Enable FOSRestBundle & NelmioApiDocBundle Ensure these are installed and configured in bundles.php:

    FOS\RestBundle\FOSRestBundle::class => ['all' => true],
    Nelmio\ApiDocBundle\NelmioApiDocBundle::class => ['all' => true],
    
  3. Configure API Routes Annotate a controller with @Rest\Route (FOSRestBundle) and @ApiDoc (NelmioApiDocBundle):

    use FOS\RestBundle\Controller\Annotations as Rest;
    use Nelmio\ApiDocBundle\Annotation\ApiDoc;
    
    class PostController extends AbstractController
    {
        /**
         * @Rest\Get("/posts")
         * @ApiDoc(
         *     resource=true,
         *     description="List all posts",
         *     statusCodes={200="OK"}
         * )
         */
        public function listPosts(): Response
        {
            return $this->json(['posts' => Post::all()]);
        }
    }
    
  4. Generate API Docs Visit /api/doc (default Nelmio route) to see auto-generated Swagger/OpenAPI docs.


Implementation Patterns

CRUD Workflows

  1. Resource Controllers Extend Chance\RestApiBridgeBundle\Controller\AbstractCrudController for auto-generated CRUD:

    use Chance\RestApiBridgeBundle\Controller\AbstractCrudController;
    
    class PostController extends AbstractCrudController
    {
        protected static $entityClass = Post::class;
        protected static $serializerGroups = ['api'];
    }
    
    • Automatically handles GET, POST, PUT, DELETE for /posts and /posts/{id}.
  2. Custom Serialization Use Symfony Serializer with groups:

    # config/packages/fos_rest.yaml
    fos_rest:
        serializer:
            groups: ['api']
    

    Define groups in your entity:

    #[ORM\Entity]
    #[ApiResource(
        collectionOperations: ['get', 'post'],
        itemOperations: ['get', 'put', 'delete']
    )]
    class Post
    {
        #[Groups(['api'])]
        private $title;
    }
    
  3. Validation & Error Handling Use Symfony Validator with custom error formats:

    use Symfony\Component\Validator\Constraints as Assert;
    
    class Post
    {
        #[Assert\NotBlank]
        #[Assert\Length(max: 255)]
        private $title;
    }
    

    Configure FOSRest to return validation errors:

    fos_rest:
        exception_handler:
            enabled: true
    
  4. Pagination Integrate with Knp\Component\PagerfantaBundle:

    use Knp\Component\PagerfantaBundle\Pagination\DoctrineORMAdapter;
    
    public function listPosts(Request $request): Response
    {
        $dql = "SELECT p FROM App\Entity\Post p";
        $pager = new Pagerfanta(new DoctrineORMAdapter($this->getDoctrine()->getManager()->createQuery($dql)));
        $pager->setMaxPerPage(10);
        return $this->handleView($this->view($pager));
    }
    
  5. Authentication & Authorization Use Symfony Security with FOSOAuthBundle or LexikJWT:

    # config/packages/security.yaml
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            jwt: ~
    

Gotchas and Tips

Pitfalls

  1. NelmioApiDocBundle Misconfiguration

    • Ensure nelmio_api_doc is properly routed in config/routes/nelmio_api_doc.yaml:
      nelmio_api_doc:
          resource: "@NelmioApiDocBundle/Resources/config/routing.yaml"
          prefix: /api/doc
      
    • Fix: Clear cache (php bin/console cache:clear) if docs don’t load.
  2. FOSRestBundle Serialization Conflicts

    • If responses are malformed, check fos_rest.serializer config:
      fos_rest:
          serializer:
              groups: ['api']  # Must match entity groups
      
    • Fix: Use #[Groups] consistently across entities and controllers.
  3. AbstractCrudController Overrides

    • Custom methods in AbstractCrudController may clash with auto-generated routes.
    • Fix: Explicitly define routes with @Rest\Route to avoid conflicts.
  4. Doctrine ORM vs. API Resources

    • If using #[ApiResource], ensure api_platform is not installed (conflict with FOSRest).
    • Fix: Remove api_platform/core if present.
  5. CORS Issues

    • NelmioApiDocBundle may block CORS requests to /api/doc.
    • Fix: Configure CORS in config/packages/nelmio_api_doc.yaml:
      nelmio_api_doc:
          areas:  # Leave empty or configure explicitly
              default:
                  path_patterns: [^/api(doc|/)]
      

Debugging Tips

  1. Check Route Debugging

    php bin/console debug:router
    

    Look for nelmio_api_doc and FOSRest routes.

  2. Enable API Debugging Add to config/packages/dev/fos_rest.yaml:

    fos_rest:
        param_fetcher_listener: true
        body_listener: true
        format_listener: true
    
  3. Log Serialization Errors Enable Symfony Profiler and check the "Response" tab for serialization issues.

Extension Points

  1. Custom Response Transformers Override FOS\RestBundle\View\View in a controller:

    return $this->view($data, 200, [], [
        'group' => ['api:custom']
    ]);
    
  2. Dynamic API Docs Extend Nelmio’s ApiDoc annotation with custom metadata:

    #[ApiDoc(
        description="Custom description",
        examples={
            "application/json"={
                "value"={"id":1,"title":"Test"},
                "summary"=>"Example response"
            }
        }
    )]
    
  3. Event Subscribers Listen to fos_rest.exception or nelmio_api_doc.event.doc:

    // src/EventListener/CustomApiDocListener.php
    public function onDoc(DocEvent $event): void
    {
        $event->getDoc()->setDescription('Custom description');
    }
    

    Register in services.yaml:

    services:
        App\EventListener\CustomApiDocListener:
            tags:
                - { name: kernel.event_listener, event: nelmio_api_doc.event.doc }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware