Skip to content

Model Class not found error in Magento REST API – not able to identify any issues in this

Error: Class "TestCsvImportModelImport" not found in /var/www/html/testproject/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php:121

This is the error I am getting. Here are my code

  1. webapi.xml
    <?xml version="1.0"?>
    <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi/etc/webapi.xsd">
        <route url="/V1/import/csv" method="POST">
            <service class="TestCsvImportApiImportInterface" method="importCsv"/>
            <resources>
                <resource ref="Magento_Backend::admin"/>
            </resources>
        </route>
    </routes>
  1. di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="TestCsvImportApiImportInterface" type="TestCsvImportModelImport" />
</config>
  1. TestCsvImportApiImportInterface.php
<?php
namespace TestCsvImportApi;

interface ImportInterface
{
    /**
     * Import CSV data
     *
     * @param string $csvData Base64 encoded CSV data
     * @return mixed
     */
    public function importCsv($csvData);
}
  1. TestCsvImportModelImport.php
<?php

namespace TestCsvImportModel;

use TestCsvImportApiImportInterface;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoFrameworkExceptionLocalizedException;

class Import implements ImportInterface
{
    /**
     * @var MagentoCatalogApiProductRepositoryInterface
     */
    protected $productRepository;
    
    /**
     * Import constructor.
     * @param MagentoCatalogApiProductRepositoryInterface $productRepository
     */
    public function __construct(
        ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
    }
    /**
     * @return bool|mixed
     * @throws Exception
    */
    public function importCsv($csvData)
    {
        echo "here";
        // Decode the CSV data
        $csvData = base64_decode($csvData);
        $rows = array_map('str_getcsv', explode("n", $csvData));

        foreach ($rows as $row) {
            // Assuming SKU is in the first column and price in the second
            $sku = $row[0];
            $price = $row[1];
            try {
                $product = $this->productRepository->get($sku);
                $product->setPrice($price);
                $this->productRepository->save($product);
            } catch (Exception $e) {
                throw new LocalizedException(__('Error updating product: %1', $e->getMessage()));
            }
        }
        return $true;
    }
}

All commands have successfully run and no issues at all. But still I am getting the error in Postman.