Get Tracking details information by Shipment id Magento 2.

You can get the Shipment Tracking information, like tracking_number, carrier code, title, order_id from the shipment id using Magento 2.

Using Magento\Sales\Api\ShipmentRepositoryInterface interface to retrieve shipment object and based on shipment object we can fetch all the tracking information for a shipment.

getTracks() method of Shipping object contains the Tracking information data.

ShipmentTrackInterface contains the basic function of Tracking Details.

<?php
namespace Jesadiya\Model\Shipment;

use Exception;
use Psr\Log\LoggerInterface;
use Magento\Sales\Api\Data\ShipmentInterface;
use Magento\Sales\Api\Data\ShipmentTrackInterface;
use Magento\Sales\Api\ShipmentRepositoryInterface;

class Tracking
{
    /**
     * @var ShipmentRepositoryInterface
     */
    private $shipmentRepository;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        ShipmentRepositoryInterface $shipmentRepository,
        LoggerInterface $logger
    ) {
        $this->shipmentRepository = $shipmentRepository;
        $this->logger = $logger;
    }

    /**
     * Get Shipment Trackig data by Shipment Id
     *
     * @param $id
     *
     * @return ShipmentTrackInterface|null
     */
    public function getTracking($id)
    {
        $shipmentId = 1; //shipment id
        $shipment = $this->getShipmentById($shipmentId);

        if ($shipment) {
            return $shipment->getTracks();
        }
        return null;
    }

    /**
     * Get Shipment data by Shipment Id
     *
     * @param $id
     *
     * @return ShipmentInterface|null
     */
    public function getShipmentById($id)
    {
        try {
            $shipment = $this->shipmentRepository->get($id);
        } catch (Exception $exception)  {
            $this->logger->critical($exception->getMessage());
            $shipment = null;
        }
        return $shipment;
    }
}

Now you can call the function under the template file or any PHP class,

$shipmentId = 1; // shipment id
$shipmment = $this->getTracking($shipmentId);
foreach ($shipment->getTracks() as $track) {
    echo $track->getTrackingNumber(); // 3333333333
    echo $track->getTitle(); //Federal Express
    echo $track->getCarrierCode(); // fedex
    echo $track->getOrderId(); //10
}

Using the above details code snippet, You can get the tracking information of shipment in Magento 2.