Magento – How to create shipment and add tracking number through API in Magento 2

apimagento2rest apishipmentshipment-tracking

I have a csv file with 3 columns with list of (increment_id, carrier_code, tracking_number). How do I Post POST these values to existing magento 2 order using API? I have managed to load the values from csv into a data array and into $incrementid, $carrier, $tracking. i'm new to API, please be detailed as possible.

<?php
$file = fopen('track.csv', 'r', '"'); // set path to the CSV file
if ($file !== false)
{
    // add logging capability
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/import-update.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);

        public function execute()
        {
        // enter the number of data fields you require the product row inside the CSV file to contain

            $required_data_fields = 3;  //number of column in csv

            while (($row = fgetcsv($this->_file, 100, ",")) !== FALSE)
            {
                $data_count = count($row);
                if ($data_count < 1) {
                    continue;
                }

                $data = array();
                //$data = array_combine($header, $row);
                $data = array($row);

                $ponumber = $row[0]; //$data['ponumber']; // column A
                if ($data_count < $required_data_fields) {
                    $logger->info("Skipping Order Number " . $ponumber . ". Not enough data to import.");
                    continue;
                }

                $shipvia = isset($row[1]) ? $row[1] : null;
                $trackingnumber =  isset($row[2]) ? $row[2] : null;

                switch ($shipvia) {
                    case "FEDEX":
                        $shipvia = "fedex";
                        break;
                    case "UPS":
                        $shipvia = "ups";
                        break;
                    case "USPS":
                        $shipvia = "usps";
                        break;
                    default:
                        $shipvia = "fedex";
                }
            }


    fclose($file); 
}

Best Answer

If you are shipping all items in the order, there is no need to actually include the items - this is all you need to create a shipment with tracking:

{
  "tracks": [
    {
      "track_number": "1Y-9876543210",
      "title": "Custom",
      "carrier_code": "SomeCarrierCode"
    }
  ]
}

As long as you have the Magento order ID in the API endpoint rest/V1/order/{order_id}/ship, this will work.

Related Topic