canaltp/navitia
PHP client for the Navitia public transport API. Configure base URL, token, timeout and other query parameters, and integrate via autowiring in Symfony/modern PHP apps. Supports caching and multiple package versions for legacy to Symfony 5.4 projects.
Installation Add the package via Composer:
composer require canaltp/navitia
Publish the config file (if needed):
php artisan vendor:publish --provider="Canaltp\Navitia\NavitiaServiceProvider"
Basic Setup
Configure your Navitia API endpoint in .env:
NAVITIA_URL=https://api.navitia.io/v1
NAVITIA_API_KEY=your_api_key_here
Register the service in config/services.php:
'navitia' => [
'url' => env('NAVITIA_URL'),
'api_key' => env('NAVITIA_API_KEY'),
],
First API Call Fetch a simple stop area (e.g., a train station) in a Laravel controller:
use Canaltp\Navitia\Facades\Navitia;
public function getStopArea($stopAreaId)
{
$stop = Navitia::stopArea($stopAreaId);
return response()->json($stop);
}
Real-Time Journey Planning
Use the journey method to fetch optimized routes between stops:
$journey = Navitia::journey([
'from' => 'stop_area_id_1',
'to' => 'stop_area_id_2',
'datetime' => now()->format('Y-m-d\TH:i:s'),
'first_index' => 0,
'last_index' => 1,
]);
Stop Area Search Search for stops by name or coordinates:
$stops = Navitia::searchStopArea('Paris', [
'coord_around_latitude' => 48.8566,
'coord_around_longitude' => 2.3522,
'radius' => 1000,
]);
Vehicle Positions (Live Tracking) Fetch real-time positions of vehicles (e.g., buses, trains):
$vehicles = Navitia::vehiclePositions('network_id', [
'datetime' => now()->format('Y-m-d\TH:i:s'),
]);
Calendar and Disruptions Check service calendars or disruptions:
$calendar = Navitia::calendar('network_id');
$disruptions = Navitia::disruptions('network_id');
Caching Responses Cache frequent API calls (e.g., stop areas, journeys) using Laravel’s cache:
$stop = Cache::remember("navitia_stop_{$stopAreaId}", now()->addHours(1), function () use ($stopAreaId) {
return Navitia::stopArea($stopAreaId);
});
Error Handling Wrap API calls in try-catch blocks to handle rate limits or invalid responses:
try {
$journey = Navitia::journey($params);
} catch (\Canaltp\Navitia\Exceptions\NavitiaException $e) {
Log::error("Navitia API Error: " . $e->getMessage());
return response()->json(['error' => 'Service unavailable'], 503);
}
Pagination
Use withPagination() for large datasets (e.g., stop areas):
$stops = Navitia::searchStopArea('Paris')->withPagination();
Webhooks for Real-Time Updates Subscribe to Navitia’s webhooks (if supported) for live disruptions or vehicle updates:
// Example: Route a webhook payload
Route::post('/navitia-webhook', function (Request $request) {
$data = $request->json()->all();
// Process real-time updates (e.g., disruptions)
});
Rate Limiting Navitia enforces rate limits (e.g., 60 requests/minute). Cache aggressively and implement exponential backoff for retries:
use Symfony\Component\HttpClient\RetryStrategy;
$client = Navitia::getClient()->withOptions([
'retry' => RetryStrategy::create(RetryStrategy::MAX_RETRIES, 1000),
]);
API Key Restrictions
Some endpoints (e.g., /journey) may require a paid API key for high-volume usage. Test with a free tier first.
Time Zone Handling Navitia uses UTC for all datetime inputs. Convert local times explicitly:
$datetime = now()->timezone('UTC')->format('Y-m-d\TH:i:s');
Deprecated Endpoints
Check the Navitia API docs for deprecated endpoints (e.g., /coverage may be replaced by /stop_areas).
Large Payloads
Journeys with many legs or stops can return huge JSON responses. Use last_index to limit results:
$journey = Navitia::journey($params)->with(['last_index' => 3]);
Enable Debug Mode
Set NAVITIA_DEBUG=true in .env to log raw API responses:
NAVITIA_DEBUG=true
Validate Parameters
Use Navitia::validateParams() to check request parameters before sending:
$params = ['from' => '123', 'to' => '456'];
if (!Navitia::validateParams($params)) {
throw new \InvalidArgumentException("Invalid parameters");
}
Mocking for Testing Use Laravel’s HTTP mocking to test without hitting the API:
$this->mock(Navitia::class, function ($mock) {
$mock->shouldReceive('journey')
->once()
->andReturn(['data' => 'mocked_response']);
});
Custom Request Transformers
Extend the Canaltp\Navitia\Transformers\Transformer class to modify responses:
class CustomTransformer extends Transformer
{
public function transformJourney($journey)
{
// Add custom logic (e.g., format durations)
return parent::transformJourney($journey);
}
}
Register it in config/navitia.php:
'transformer' => \App\Transformers\CustomTransformer::class,
Middleware for Authentication Add middleware to inject headers (e.g., custom auth tokens):
Navitia::getClient()->withOptions([
'headers' => [
'X-Custom-Header' => 'value',
],
]);
Event Listeners Dispatch events for critical API responses (e.g., disruptions):
event(new \App\Events\NavitiaDisruptionDetected($disruptionData));
How can I help you explore Laravel packages today?