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 Server Bundle Laravel Package

da/api-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    • Add dependencies to composer.json:
      "require": {
          "da/auth-common-bundle": "dev-master",
          "da/api-server-bundle": "dev-master"
      }
      
    • Run composer update (or composer.phar update on Linux).
    • Register the bundle in AppKernel.php:
      new Da\ApiServerBundle\DaApiServerBundle(),
      
  2. Basic Configuration

    • Configure security in security.yml to enable API token validation:
      security:
          firewalls:
              api:
                  pattern:   ^/api
                  da_api:    true
                  stateless: true
      
    • Ensure the X-API-Security-Token header is sent with requests.
  3. First Use Case

    • Create a controller extending Da\ApiServerBundle\Controller\ApiController:
      use Da\ApiServerBundle\Controller\ApiController;
      
      class MyApiController extends ApiController {
          public function getAction() {
              return $this->json(['data' => 'Hello, API!']);
          }
      }
      
    • Route it in routing.yml:
      my_api:
          path:     /api/hello
          defaults: { _controller: MyBundle:MyApi:get }
      

Implementation Patterns

Workflows

  1. Token-Based Authentication

    • Use X-API-Security-Token for stateless API authentication.
    • Validate tokens via security.yml firewall configuration.
    • Extend Da\ApiServerBundle\Security\ApiTokenAuthenticator for custom logic.
  2. OAuth2 Support

    • Configure Authorization: Bearer <token> in security.yml:
      api:
          pattern:   ^/api/oauth
          da_api:    true
          stateless: true
          oauth:     true
      
    • Integrate with OAuth2 providers (e.g., league/oauth2-server).
  3. Resource Controllers

    • Extend ApiController for CRUD operations:
      class UserApiController extends ApiController {
          public function getUserAction($id) {
              $user = $this->getDoctrine()->getRepository('App:User')->find($id);
              return $this->json($user);
          }
      }
      
    • Use json() for responses and getRequest() for input validation.
  4. Middleware Integration

    • Chain with Symfony’s event system (e.g., kernel.request):
      $event->getResponse()->headers->set('X-API-Version', '1.0');
      

Integration Tips

  • Doctrine ORM: Inject EntityManager via dependency injection:
    public function __construct(EntityManagerInterface $em) {
        $this->em = $em;
    }
    
  • Validation: Use Symfony’s Validator component:
    $errors = $this->get('validator')->validate($data);
    
  • CORS: Configure CORS headers in a listener:
    $response->headers->set('Access-Control-Allow-Origin', '*');
    

Gotchas and Tips

Pitfalls

  1. Deprecated Dependencies

    • The bundle relies on da/auth-common-bundle (unmaintained since 2014). Fork or replace with modern alternatives (e.g., lexik/jwt-authentication-bundle).
    • Workaround: Override authentication logic in a custom bundle.
  2. Security Quirks

    • No built-in rate limiting or IP whitelisting. Implement via:
      # security.yml
      api:
          pattern:   ^/api
          da_api:    true
          stateless: true
          ip_whitelist: [192.168.1.0/24]  # Custom extension
      
    • Tip: Use monolog for logging failed token attempts.
  3. Routing Conflicts

    • Prefix API routes with /api to avoid clashes with frontend routes.
    • Debugging: Use php bin/console debug:router to verify routes.
  4. OAuth2 Limitations

    • No built-in token refresh or revocation. Use league/oauth2-server alongside.

Debugging

  • Token Validation Failures

    • Check X-API-Security-Token header presence and security.yml config.
    • Enable debug mode (APP_DEBUG=true) for detailed errors.
  • 403 Forbidden Errors

    • Ensure the da_api firewall is correctly applied to the route pattern.
    • Verify the stateless: true setting for API endpoints.

Extension Points

  1. Custom Authenticators

    • Extend Da\ApiServerBundle\Security\ApiTokenAuthenticator:
      class CustomAuthenticator extends ApiTokenAuthenticator {
          public function authenticateToken($token) {
              // Custom logic (e.g., DB lookup)
              return $user;
          }
      }
      
    • Register in security.yml:
      api:
          pattern:   ^/api
          da_api:    true
          stateless: true
          authenticator: your.bundle.custom_authenticator
      
  2. Response Transformers

    • Override Da\ApiServerBundle\Response\JsonResponse for custom serialization:
      class CustomJsonResponse extends JsonResponse {
          public function setData($data, $status = 200, array $headers = []) {
              $data['meta'] = ['timestamp' => time()];
              parent::setData($data, $status, $headers);
          }
      }
      
  3. Event Listeners

    • Subscribe to api.security.token.validated:
      $eventDispatcher->addListener('api.security.token.validated', function ($event) {
          $event->getUser()->addRole('API_USER');
      });
      

Configuration Quirks

  • Header Case Sensitivity
    • The bundle expects X-API-Security-Token (exact case). Use strtoupper() if needed:
      $token = strtoupper($request->headers->get('x-api-security-token'));
      
  • Caching Tokens
    • For performance, cache validated tokens (e.g., with symfony/cache):
      $cache = $this->get('cache.app');
      $token = $cache->get('api_token_' . $tokenHash);
      
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views