Skip to main content
1 of 3

How to save data to database using interface repository api

I'm a newbie magento 2 developer. I'm currently learning how to store data to database using repository-interface-model-api approach. My code is not working.

model ItemRepository

    /**
     * {@inheritdoc}
     */
    public function save(ItemInterface $article)
    {
        try {
            /** @var Article $article */
            $article->getResource()->save($article);
        } catch (\Exception $exception) {
            throw new CouldNotSaveException(
                __(sprintf('Could not save Article: %s', $exception->getMessage()))
            );
        }
        return $article;
    }

Api - Data ItemInterface

interface ItemInterface
{
    const ARTICLE_ID            = 'article_id';
    const TITLE                 = 'title';
    const CONTENT               = 'content';
    const CREATED_AT            = 'created_at';
    
   /**
     * Get Title
     *
     * @return string|null
     */
    public function getTitle();

    /**
     * Get Content
     *
     * @return string|null
     */
    public function getContent();

    /**
     * Get Created At
     *
     * @return string|null
     */
    public function getCreatedAt();

    /**
     * Get ID
     *
     * @return int|null
     */
    public function getId();

    /**
     * Set Title
     *
     * @param string $title
     * @return $this
     */
    public function setTitle($title);

    /**
     * Set Content
     *
     * @param string $content
     * @return $this
     */
    public function setContent($content);

    /**
     * Set Crated At
     *
     * @param int $createdAt
     * @return $this
     */
    public function setCreatedAt($createdAt);

    /**
     * Set ID
     *
     * @param int $id
     * @return $this
     */
    public function setId($id);
}

Api - ItemRepository

interface ItemRepositoryInterface
{
    /**
     * @return \Thecoachsmb\Mymodule\Api\Data\ItemInterface[]
     */
    public function getList();

    /**
     * @param ItemInterface $article
     * @return ItemInterface
     */
    public function save(ItemInterface $article);

}

Model-ResourceModel-Item - Collection

class Collection extends AbstractCollection
{
    
    protected function _construct()
    {
        $this->_init(
            Item::class,
            ItemResource::class
        );
    }
}

Model-ResourceModel-Item

class Item extends AbstractDb 
{
    protected function _construct()
    {
        $this->_init('test', 'article_id');
    }
}

Model-Item

class Item extends AbstractModel implements ItemInterface, IdentityInterface
{


    /**
     * Post Initialization
     * @return void
     */
    protected function _construct()
    {
        $this->_init(Item::class);
    }

  /**
     * Get Title
     *
     * @return string|null
     */
    public function getTitle()
    {
        return $this->getData(self::TITLE);
    }

    /**
     * Get Content
     *
     * @return string|null
     */
    public function getContent()
    {
        return $this->getData(self::CONTENT);
    }

    /**
     * Get Created At
     *
     * @return string|null
     */
    public function getCreatedAt()
    {
        return $this->getData(self::CREATED_AT);
    }

    /**
     * Get ID
     *
     * @return int|null
     */
    public function getId()
    {
        return $this->getData(self::ARTICLE_ID);
    }

    /**
     * Return identities
     * @return string[]
     */
    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->getId()];
    }

    /**
     * Set Title
     *
     * @param string $title
     * @return $this
     */
    public function setTitle($title)
    {
        return $this->setData(self::TITLE, $title);
    }

    /**
     * Set Content
     *
     * @param string $content
     * @return $this
     */
    public function setContent($content)
    {
        return $this->setData(self::CONTENT, $content);
    }

    /**
     * Set Created At
     *
     * @param string $createdAt
     * @return $this
     */
    public function setCreatedAt($createdAt)
    {
        return $this->setData(self::CREATED_AT, $createdAt);
    }

    /**
     * Set ID
     *
     * @param int $id
     * @return $this
     */
    public function setId($id)
    {
        return $this->setData(self::ARTICLE_ID, $id);
    }
}

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="Thecoachsmb\Mymodule\Api\Data\ItemInterface" type="Thecoachsmb\Mymodule\Model\Item"/>
    <preference for="Thecoachsmb\Mymodule\Api\ItemRepositoryInterface" type="Thecoachsmb\Mymodule\Model\ItemRepository"/>
</config>

webapi.xml

<?xml version="1.0"?>
<routes>
    <route url="/V1/article" method="GET">
        <service class="Thecoachsmb\Mymodule\Api\ItemRepositoryInterface" method="getList"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

     <route url="/V1/article" method="POST">
        <service class="Sample\Mymodule\Api\ItemRepositoryInterface" method="save"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

api call:POST http://localhost/rest/V1/article?title=Test title&content=test content

Any idea what is wrong with my code? Thanks in advance