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

Navitiaio Api Bundle Laravel Package

canaltp/navitiaio-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your project via Composer:

    composer require canaltp/navitiaio-api-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        CanalTP\NavitiaIoApiBundle\NavitiaIoApiBundle::class => ['all' => true],
    ];
    
  2. Configuration Define your Navitia API credentials in config/packages/navitia_io_api.yaml:

    navitia_io_api:
        api_key: '%env(NAVITIA_API_KEY)%'
        base_uri: '%env(NAVITIA_BASE_URI)%'
        timeout: 30
    
  3. First Use Case Inject the NavitiaIoApi service in a controller or service:

    use CanalTP\NavitiaIoApiBundle\Service\NavitiaIoApi;
    
    class TripController extends AbstractController
    {
        public function __construct(private NavitiaIoApi $navitiaApi) {}
    
        public function getTripDetails(string $tripId): JsonResponse
        {
            $trip = $this->navitiaApi->get('/v1/trips/{tripId}', [
                'headers' => ['Accept' => 'application/json'],
            ]);
            return $this->json($trip);
        }
    }
    

Implementation Patterns

Common Workflows

  1. API Requests Use the service for standard HTTP requests with automatic authentication:

    $response = $this->navitiaApi->get('/v1/coverage/fr-idf', [
        'query' => ['date' => 'today'],
    ]);
    
  2. Pagination Handling Iterate over paginated results:

    $page = 1;
    do {
        $results = $this->navitiaApi->get('/v1/stops', [
            'query' => ['page' => $page],
        ]);
        // Process $results
        $page++;
    } while (!empty($results['_links']['next']));
    
  3. Error Handling Wrap API calls in try-catch blocks:

    try {
        $data = $this->navitiaApi->post('/v1/stop_areas', ['json' => $stopAreaData]);
    } catch (NavitiaIoApiException $e) {
        $this->addFlash('error', $e->getMessage());
        return $this->redirectToRoute('home');
    }
    
  4. Caching Responses Cache frequent queries (e.g., coverage data):

    $cacheKey = 'navitia_coverage_fr-idf';
    $coverage = $this->navitiaApi->getCached($cacheKey, '/v1/coverage/fr-idf', 3600);
    

Integration Tips

  • Symfony Messenger: Dispatch API calls as messages for async processing.
  • Doctrine ORM: Map Navitia responses to Doctrine entities using Hydrator.
  • API Versioning: Use the version query parameter for backward compatibility:
    $this->navitiaApi->get('/v1/stop_areas', ['query' => ['version' => 'v1.2']]);
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting Navitia Io may throttle requests. Implement exponential backoff:

    $this->navitiaApi->setRetryStrategy(new RetryStrategy(3, 100));
    
  2. Deprecated Endpoints Monitor Navitia’s API changelog for deprecated routes (e.g., /v0/ → /v1/).

  3. Case Sensitivity Endpoints like /v1/stop_areas are case-sensitive. Use the exact path from the API docs.

  4. Large Payloads Avoid sending large JSON payloads in POST/PUT requests. Stream data or chunk uploads.

Debugging

  • Enable Verbose Logging Configure Monolog to log API requests:

    # config/packages/monolog.yaml
    handlers:
        navitia:
            type: stream
            path: "%kernel.logs_dir%/navitia.log"
            level: debug
            channels: ["navitia_io"]
    

    Then enable channel in NavitiaIoApi:

    $this->navitiaApi->setLogger($this->container->get('monolog.logger.navitia'));
    
  • Inspect Raw Responses Use getRawResponse() to debug headers/status codes:

    $response = $this->navitiaApi->get('/v1/stop_areas');
    $raw = $response->getRawResponse();
    

Extension Points

  1. Custom HTTP Clients Replace the default GuzzleHttp\Client by binding a custom client:

    # config/services.yaml
    services:
        CanalTP\NavitiaIoApiBundle\Service\NavitiaIoApi:
            arguments:
                $client: '@custom.http.client'
    
  2. Middleware Add request/response middleware:

    $this->navitiaApi->getClient()->getEmitter()->addSubscriber(
        new AddAuthHeaderMiddleware('X-Custom-Header', 'value')
    );
    
  3. Event Listeners Subscribe to NavitiaIoApiEvent for pre/post-request logic:

    $dispatcher->addListener(NavitiaIoApiEvent::PRE_REQUEST, function (NavitiaIoApiEvent $event) {
        $event->setOption('headers', ['X-Request-ID' => uniqid()]);
    });
    
  4. Testing Mock the NavitiaIoApi service in PHPUnit:

    $mockApi = $this->createMock(NavitiaIoApi::class);
    $mockApi->method('get')->willReturn(['data' => 'mocked']);
    $this->container->set('navitia_io_api', $mockApi);
    
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.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log