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

Api Bundle Laravel Package

ekyna/api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ekyna/api-bundle:^0.8
    

    Register the bundle in config/bundles.php:

    Ekyna\Bundle\ApiBundle\EkynaApiBundle::class => ['all' => true],
    
  2. Basic Configuration: Add the routing prefix in config/packages/ekyna_api.yaml:

    ekyna_api:
        routing_prefix: /api
    
  3. First Use Case: Extend an existing EkynaResourceBundle entity to expose API endpoints. For example, if you have a User entity managed by EkynaResourceBundle, the API endpoints (/api/users, /api/users/{id}) will be auto-generated.


Implementation Patterns

1. Resource-Based API Endpoints

  • Automatic CRUD Endpoints: The bundle leverages EkynaResourceBundle to auto-generate RESTful endpoints for entities. No manual controller creation is needed for basic CRUD operations.

    # config/packages/ekyna_resource.yaml
    ekyna_resource:
        resources:
            App\Entity\User:
                collection: true
                item: true
    
  • Customization via Annotations: Use annotations to override default behavior (e.g., @Ekyna\Resource\Annotation\Api\ApiResource):

    use Ekyna\Resource\Annotation\Api\ApiResource;
    
    /**
     * @ApiResource(
     *     collectionOperations={"get", "post"},
     *     itemOperations={"get", "put", "delete"}
     * )
     */
    class User {}
    

2. Request/Response Transformation

  • Serialization Groups: Use Symfony’s Serializer component with groups to control API payloads:

    use Symfony\Component\Serializer\Annotation\Groups;
    
    class User {
        /**
         * @Groups({"user:read"})
         */
        private $name;
    }
    
  • Custom Serializers: Extend the default serializer behavior by implementing Ekyna\Resource\Serializer\SerializerInterface and binding it in the container:

    services:
        App\Serializer\CustomUserSerializer:
            tags: ['ekyna.resource.serializer']
    

3. Authentication and Authorization

  • JWT Integration: Pair with lexik/jwt-authentication-bundle for token-based auth. Configure the EkynaApiBundle to protect routes:

    ekyna_api:
        security:
            enabled: true
            provider: lexik_jwt_authentication.jwt_token_authenticator
    
  • Role-Based Access: Use Symfony’s voter system or EkynaResourceBundle’s @AccessControl annotation:

    use Ekyna\Resource\Annotation\AccessControl;
    
    /**
     * @AccessControl("is_granted('ROLE_ADMIN')")
     */
    class AdminUser {}
    

4. Pagination and Filtering

  • Default Pagination: Enable via config:

    ekyna_api:
        pagination:
            enabled: true
            items_per_page: 20
    
  • Custom Filters: Create a filter class and tag it as a ekyna.resource.filter service:

    use Ekyna\Resource\Filter\FilterInterface;
    
    class ActiveUserFilter implements FilterInterface {
        // ...
    }
    
    services:
        App\Filter\ActiveUserFilter:
            tags: ['ekyna.resource.filter']
    

5. Event-Driven Extensions

  • Pre/Post Hooks: Subscribe to events like ekyna.resource.pre_collection or ekyna.resource.post_item:
    use Ekyna\Resource\Event\ResourceEvent;
    
    $eventDispatcher->addListener(ResourceEvent::PRE_COLLECTION, function (ResourceEvent $event) {
        // Modify query or request before processing
    });
    

Gotchas and Tips

Pitfalls

  1. Bundle Dependency:

    • EkynaApiBundle requires EkynaResourceBundle. Ensure both are installed and configured.
    • Fix: Verify EkynaResourceBundle is registered in config/bundles.php and properly configured.
  2. Routing Conflicts:

    • The /api prefix may clash with other bundles (e.g., Symfony’s api_platform).
    • Fix: Adjust routing_prefix or use a unique namespace:
      ekyna_api:
          routing_prefix: /v1
      
  3. Serialization Mismatches:

    • If payloads don’t match expectations, check:
      • Serialization groups (@Groups).
      • Custom serializers (priority in ekyna.resource.serializer tags).
    • Debug: Use debug:container ekyna.resource.serializer to inspect registered serializers.
  4. Caching Issues:

    • API responses may not update if the cache is aggressive.
    • Fix: Disable cache for development or use EkynaResourceBundle’s cache invalidation:
      framework:
          cache:
              pools: false  # Disable for debugging
      
  5. Annotation Overrides:

    • Annotations on entities take precedence over YAML config. Test changes thoroughly.
    • Tip: Use Ekyna\Resource\Annotation\AnnotationReader to inspect parsed annotations.

Debugging Tips

  1. Enable API Debug Mode:

    ekyna_api:
        debug: true  # Logs requests/responses to Symfony profiler
    
  2. Inspect Events:

    • Use the Symfony profiler (/_profiler) to trace Ekyna\Resource\Event listeners.
  3. Check Route Generation:

    • Dump routes to verify endpoints:
      php bin/console debug:router | grep ekyna
      

Extension Points

  1. Custom API Platform:

    • Override the default EkynaApiBundle\Api\ApiPlatform by binding your implementation:
      services:
          App\Api\CustomApiPlatform:
              decorates: 'ekyna.api.api_platform'
              arguments: ['@.inner']
      
  2. Dynamic Route Naming:

    • Extend Ekyna\Resource\Routing\Router to customize route names:
      use Ekyna\Resource\Routing\RouterInterface;
      
      class CustomRouter implements RouterInterface {
          public function generate(string $name, array $parameters = []): string {
              // Custom logic
          }
      }
      
      services:
          App\Routing\CustomRouter:
              decorates: 'ekyna.resource.router'
      
  3. API Documentation:

    • Integrate with nelmio/api-doc-bundle by extending the EkynaApiBundle’s documentation provider:
      use Ekyna\Bundle\ApiBundle\Documentation\ApiDocumentation;
      
      class CustomApiDocumentation extends ApiDocumentation {
          public function getPaths(): array {
              // Add custom paths
          }
      }
      
      services:
          App\Documentation\CustomApiDocumentation:
              decorates: 'ekyna.api.documentation'
      

Configuration Quirks

  1. Priority in YAML vs. Annotations:

    • YAML config in ekyna_api is global; annotations are per-entity. Annotations override YAML for specific cases.
  2. Security Provider:

    • If security.enabled: true, ensure the provider (e.g., lexik_jwt_authentication.jwt_token_authenticator) is correctly configured in Symfony’s security.yaml.
  3. Pagination Defaults:

    • items_per_page applies to all collections unless overridden per-entity:
      /**
       * @ApiResource(
       *     paginationItemsPerPage=50
       * )
       */
      class LargeDataset {}
      
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