Table of Contents for
Magento 2 Development Quick Start Guide

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Magento 2 Development Quick Start Guide by Branko Ajzele Published by Packt Publishing, 2018
  1. Magento 2 Development Quick Start Guide
  2. Title Page
  3. Copyright and Credits
  4. Magento 2 Development Quick Start Guide
  5. Packt Upsell
  6. Why subscribe?
  7. Packt.com
  8. Contributors
  9. About the author
  10. About the reviewer
  11. Packt is searching for authors like you
  12. Table of Contents
  13. Preface
  14. Who this book is for
  15. What this book covers
  16. To get the most out of this book
  17. Download the example code files
  18. Code in Action
  19. Conventions used
  20. Get in touch
  21. Reviews
  22. Understanding the Magento Architecture
  23. Technical requirements
  24. Installing Magento
  25. Modes
  26. Areas
  27. Request flow processing
  28. Modules
  29. Creating the minimal module
  30. Cache
  31. Dependency injection
  32. Argument injection
  33. Virtual types
  34. Proxies
  35. Factories
  36. Plugins
  37. The before plugin
  38. The around plugin
  39. The after plugin
  40. Events and observers
  41. Console commands
  42. Cron jobs
  43. Summary
  44. Working with Entities
  45. Technical requirements
  46. Understanding types of models
  47. Creating a simple model
  48. Methods worth memorizing
  49. Working with setup scripts
  50. The InstallSchema script
  51. The UpgradeSchema script
  52. The Recurring script
  53. The InstallData script
  54. The UpgradeData script
  55. The RecurringData script
  56. Extending entities
  57. Creating extension attributes
  58. Summary
  59. Understanding Web APIs
  60. Technical requirements
  61. Types of users
  62. Types of authentication
  63. Types of APIs
  64. Using existing web APIs
  65. Creating custom web APIs
  66. Understanding search criteria
  67. Summary
  68. Building and Distributing Extensions
  69. Technical requirements
  70. Building a shipping extension
  71. Distributing via GitHub
  72. Distributing via Packagist
  73. Summary
  74. Developing for Admin
  75. Technical requirements
  76. Using the listing component
  77. Using the form component
  78. Summary
  79. Developing for Storefront
  80. Technical requirements
  81. Setting up the playground
  82. Calling and initializing JS components
  83. Meet RequireJS
  84. Replacing jQuery widget components
  85. Extending jQuery widget components
  86. Creating jQuery widgets components
  87. Creating UI/KnockoutJS components
  88. Extending UI/KnockoutJS components
  89. Summary
  90. Customizing Catalog Behavior
  91. Technical requirements
  92. Creating the size guide
  93. Creating the same day delivery
  94. Flagging new products
  95. Summary
  96. Customizing Checkout Experiences
  97. Technical requirements
  98. Passing data to the checkout
  99. Adding order notes to the checkout
  100. Summary
  101. Customizing Customer Interactions
  102. Technical requirements
  103. Understanding the section mechanism
  104. Adding contact preferences to customer accounts
  105. Adding contact preferences to the checkout
  106. Summary
  107. Other Books You May Enjoy
  108. Leave a review - let other readers know what you think

Creating custom web APIs

Let's go ahead and create a miniature, yet full-blown Magento module Magelicious_Boxy that demonstrates the entire flow of creating a custom web API.

We start off by defining a module <MAGELICIOUS_DIR>/Boxy/registration.php as follows:

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Magelicious_Boxy',
__DIR__
);

We then define the <MAGELICIOUS_DIR>/Boxy/etc/module.xml as follows:

<config>
<module name="Magelicious_Boxy" setup_version="2.0.2"/>
</config>

We then define the <MAGELICIOUS_DIR>/Boxy/Setup/InstallSchema.php that adds the following table:

$table = $setup->getConnection()
->newTable($setup->getTable('magelicious_boxy_box'))
->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null, [
'identity' => true,
'unsigned' => true,
'nullable' => false,
'primary' => true
], 'Entity ID'
)
->addColumn(
'title',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
['nullable' => false], 'Title'
)
->addColumn(
'content',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
null,
['nullable' => false], 'Content'
)
->setComment('Magelicious Boxy Box Table');
$setup->getConnection()->createTable($table);

We then define <MAGELICIOUS_DIR>/Boxy/Api/Data/BoxInterface.php as follows:

interface BoxInterface {
const BOX_ID = 'box_id';
const TITLE = 'title';
const CONTENT = 'content';
public function getId();
public function getTitle();
public function getContent();
public function setId($id);
public function setTitle($title);
public function setContent($content);
}

We then define <MAGELICIOUS_DIR>/Boxy/Api/Data/BoxSearchResultsInterface.php as follows:

interface BoxSearchResultsInterface extends \Magento\Framework\Api\SearchResultsInterface
{
public function getItems();
public function setItems(array $items);
}

We then add the <MAGELICIOUS_DIR>/Boxy/Api/BoxRepositoryInterface.php as follows:

interface BoxRepositoryInterface
{
public function save(\Magelicious\Boxy\Api\Data\BoxInterface $box);
public function getById($boxId);
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
public function delete(\Magelicious\Boxy\Api\Data\BoxInterface $box);
public function deleteById($boxId);
}

We then define the <MAGELICIOUS_DIR>/Boxy/Model/Box.php as follows:

class Box extends \Magento\Framework\Model\AbstractModel implements \Magelicious\Boxy\Api\Data\BoxInterface
{
protected function _construct() {
$this->_init(\Magelicious\Boxy\Model\ResourceModel\Box::class);
}

public function getId() {
return $this->getData(self::BOX_ID);
}

public function getTitle() {
return $this->getData(self::TITLE);
}

public function getContent() {
return $this->getData(self::CONTENT);
}

public function setId($id) {
return $this->setData(self::BOX_ID, $id);
}

public function setTitle($title) {
return $this->setData(self::TITLE, $title);
}

public function setContent($content) {
return $this->setData(self::CONTENT, $content);
}
}

We then define the <MAGELICIOUS_DIR>/Boxy/Model/ResourceModel/Box.php as follows:

class Box extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
protected function _construct() {
$this->_init('magelicious_boxy_box', 'entity_id');
}
}

We then define the <MAGELICIOUS_DIR>/Boxy/Model/ResourceModel/Box/Collection.php as follows:

class Collection
{
protected function _construct() {
$this->_init(
\Magelicious\Boxy\Model\Box::class,
\Magelicious\Boxy\Model\ResourceModel\Box::class
);
}
}

We then define the <MAGELICIOUS_DIR>/Boxy/Model/BoxRepository.php as follows:

class BoxRepository implements \Magelicious\Boxy\Api\BoxRepositoryInterface
{
protected $boxFactory;
protected $boxResourceModel;
protected $searchResultsFactory;
protected $collectionProcessor;

public function __construct(
\Magelicious\Boxy\Api\Data\BoxInterfaceFactory $boxFactory,
\Magelicious\Boxy\Model\ResourceModel\Box $boxResourceModel,
\Magelicious\Boxy\Api\Data\BoxSearchResultsInterfaceFactory $searchResultsFactory,
\Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface $collectionProcessor
)
{
$this->boxFactory = $boxFactory;
$this->boxResourceModel = $boxResourceModel;
$this->searchResultsFactory = $searchResultsFactory;
$this->collectionProcessor = $collectionProcessor;
}
// Todo...
}

Let's go ahead and amend the BoxRepository with the save method as follows:

public function save(\Magelicious\Boxy\Api\Data\BoxInterface $box)
{
try {
$this->boxResourceModel->save($box);
} catch (\Exception $e) {
throw new \Magento\Framework\Exception\CouldNotSaveException(__($e->getMessage()));
}
return $box;
}

Let's go ahead and amend the BoxRepository with the getById method as follows:

public function getById($boxId) {
$box = $this->boxFactory->create();
$this->boxResourceModel->load($box, $boxId);
if (!$box->getId()) {
throw new \Magento\Framework\Exception\NoSuchEntityException(__('Box with id "%1" does not exist.', $boxId));
}
return $box;
}

Let's go ahead and amend the BoxRepository with the getList method as follows:

public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria) {
$collection = $this->boxCollectionFactory->create();
$this->collectionProcessor->process($searchCriteria, $collection);
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($searchCriteria);
$searchResults->setItems($collection->getItems());
$searchResults->setTotalCount($collection->getSize());
return $searchResults;
}

Let's go ahead and amend the BoxRepository with the delete method as follows:

public function delete(\Magelicious\Boxy\Api\Data\BoxInterface $box) {
try {
$this->boxResourceModel->delete($box);
} catch (\Exception $e) {
throw new \Magento\Framework\Exception\CouldNotDeleteException(__($e->getMessage()));
}
return true;
}

Let's go ahead and amend the BoxRepository with the deleteById method as follows:

public function deleteById($boxId) {
return $this->delete($this->getById($boxId));
}

We then define the <MAGELICIOUS_DIR>/Boxy/etc/di.xml as follows:

<config>
<preference for="Magelicious\Boxy\Api\Data\BoxInterface" type="Magelicious\Boxy\Model\Box"/>
<preference for="Magelicious\Boxy\Api\Data\BoxSearchResultsInterface" type="Magento\Framework\Api\SearchResults" />
<preference for="Magelicious\Boxy\Api\BoxRepositoryInterface" type="Magelicious\Boxy\Model\BoxRepository"/>
</config>

We then define the <MAGELICIOUS_DIR>/Boxy/etc/acl.xml as follows:

<config>
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="Magento_Sales::sales">
<resource id="Magento_Sales::sales_operation">
<resource id="Magento_Sales::shipment">
<resource id="Magelicious_Boxy::box" title="Boxy Box">
<resource id="Magelicious_Boxy::box_get" title="Get"/>
<resource id="Magelicious_Boxy::box_search" title="Search"/>
<resource id="Magelicious_Boxy::box_save" title="Save"/>
<resource id="Magelicious_Boxy::box_update" title="Update"/>
<resource id="Magelicious_Boxy::box_delete" title="Delete"/>
</resource>
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>

We then define the <MAGELICIOUS_DIR>/Boxy/etc/webapi.xml as follows:

<routes>
<route url="/V1/boxyBox/:boxId" method="GET">
<service class="Magelicious\Boxy\Api\BoxRepositoryInterface" method="getById"/>
<resources>
<resource ref="Magelicious_Boxy::box_get"/>
</resources>
</route>
<route url="/V1/boxyBox/search" method="GET">
<service class="Magelicious\Boxy\Api\BoxRepositoryInterface" method="getList"/>
<resources>
<resource ref="Magelicious_Boxy::box_search"/>
</resources>
</route>
<route url="/V1/boxyBox" method="POST">
<service class="Magelicious\Boxy\Api\BoxRepositoryInterface" method="save"/>
<resources>
<resource ref="Magelicious_Boxy::box_save"/>
</resources>
</route>
<route url="/V1/boxyBox/:id" method="PUT">
<service class="Magelicious\Boxy\Api\BoxRepositoryInterface" method="save"/>
<resources>
<resource ref="Magelicious_Boxy::box_update"/>
</resources>
</route>
<route url="/V1/boxyBox/:boxId" method="DELETE">
<service class="Magelicious\Boxy\Api\BoxRepositoryInterface" method="deleteById"/>
<resources>
<resource ref="Magelicious_Boxy::box_delete"/>
</resources>
</route>
</routes>

With all these bits in place, our API is now ready. We should now be able to CRUD our way through Boxy Box the same way we did with the CMS block. While there certainly is a great deal of boilerplate code to go around, our API is now both REST-and SOAP-ready.