You could follow Alan Kent’s Blog to learn the fundamental knowledge about Magento 2 Api
Step 1: Create a new Module and Enable it
registration.php file
#create a file at app/code/Jeff/Slider/registration.php
module.xml file
#create a file at app/code/Jeff/Slider/etc/module.xml
**Run php bin/magento module:enable Jeff_Slider to enable our new Module. But don’t run php bin/magento setup:upgrade command right now.
Step 2: Create CRUD Model for our new Module
Create InstallSchema.php file
#create a file at app/code/Jeff/Slider/Setup/InstallSchema.php startSetup(); //START: install stuff //END: install stuff //START table setup $table = $installer->getConnection()->newTable( $installer->getTable('jeff_slider_slide') )->addColumn( 'slide_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, [ 'identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true, ], 'Entity ID' )->addColumn( 'title', \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 255, [ 'nullable' => false, ], 'Demo Title' )->addColumn( 'creation_time', \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, null, [ 'nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT, ], 'Creation Time' )->addColumn( 'update_time', \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, null, [ 'nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE, ], 'Modification Time' )->addColumn( 'is_active', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, [ 'nullable' => false, 'default' => '1', ], 'Is Active' ); $installer->getConnection()->createTable($table); //END table setup $installer->endSetup(); } }
Create ACL xml file to authorize use to access our REST API
#create a file at app/code/Jeff/Slider/etc/acl.xml
Create webapi.xml file to setup access point
#create file at app/code/Jeff/Slider/etc/webapi.xml
**You can now run php bin/magento setup:upgrade command to install our database
Create di.xml file
#create dependency injection file at app/code/Jeff/Slider/etc/di.xml
Step 3: Create our model resource and API functions
create SlideRepositoryInterface.php
#create a file at app/code/Jeff/Slider/Api/SlideRepositoryInterface.php
Create SliderInterface.php file
#create a file at app/code/Jeff/Slider/Api/Data/SlideInterface.php
Create our model Slide.php
#create a file at app/code/Jeff/Slider/Model/Slide.php _init('Jeff\Slider\Model\ResourceModel\Slide'); } public function getIdentities() { return [self::CACHE_TAG . '_' . $this->getId()]; } /** * @api * @return int|null */ public function getId() { return $this->getData(self::PROPERTY_ID); } /** * @api * @param int $id * @return \Jeff\Slider\Model\Slide */ public function setId($id) { $this->setData(self::PROPERTY_ID, $id); return $this; } /** * @api * @return int|null */ public function getSlideId() { return $this->getData(self::PROPERTY_SLIDE_ID); } /** * @api * @param int $slideId * @return \Jeff\Slider\Model\Slide */ public function setSlideId($slideId) { $this->setData(self::PROPERTY_SLIDE_ID, $slideId); return $this; } /** * @api * @return string|null */ public function getTitle() { return $this->getData(self::PROPERTY_TITLE); } /** * @api * @param string $title * @return \Jeff\Slider\Model\Slide */ public function setTitle($title) { $this->setData(self::PROPERTY_TITLE, $title); } }
Create SlideInterface.php file
#create a file at app/code/Jeff/Slider/Model/SlideInterface.php
Create our model resource file Slide.php
#create a file at app/code/Jeff/Slider/Model/ResourceModel/Slide.php _init('jeff_slider_slide','slide_id'); } }
Create Our model collection Collection.php
#create a file at app/code/Jeff/Slider/Model/ResourceModel/Slide/Collection.php _init('Jeff\Slider\Model\Slide','Jeff\Slider\Model\ResourceModel\Slide'); } }
Create our model repository file SlideRepository.php
#create a file at app/code/Jeff/Slider/Model/SlideRepository.php resource = $resource; $this->slideFactory = $slideFactory; $this->slideCollectionFactory = $slideCollectionFactory; $this->searchResultsFactory = $searchResultsFactory; $this->dataObjectHelper = $dataObjectHelper; $this->dataObjectProcessor = $dataObjectProcessor; $this->dataSlideFactory = $dataSlideFactory; } /** * @api * @param \Jeff\Slider\Api\Data\SlideInterface $slide * @return \Jeff\Slider\Api\Data\SlideInterface */ public function save(\Jeff\Slider\Api\Data\SlideInterface $slide) { try { $this->resource->save($slide); } catch(\Exception $e) { throw new CouldNotSaveException(__($e->getMessage())); } return $slide; } /** * @api * @param int $slideId * @return \Jeff\Slider\Api\Data\SlideInterface */ public function getById($slideId) { $slide = $this->slideFactory->create(); $this->resource->load($slide, $slideId); if (!$slide->getId()) { throw new NoSuchEntityException(__('Object with id "%1" does not exist.', $slideId)); } return $slide; } /** * @api * @param \Jeff\Slider\Api\Data\SlideInterface $slide * @return bool ture if success */ public function delete(\Jeff\Slider\Api\Data\SlideInterface $slide) { try { $this->resource->delete($slide); } catch (\Exception $exception) { throw new CouldNotDeleteException(__($exception->getMessage())); } return true; } /** * @api * @param int $id * return bool true on success */ public function deleteById($id) { return $this->delete($this->getById($id)); } /** * @api * @param \Magento\Framework\Api\SearchCriteriaInterface $criteria * @return \Magento\Framework\Api\SearchResultsInterface */ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria) { //echo get_class($this->searchResultsFactory). "\n\n"; $searchResults = $this->searchResultsFactory; //->create(); $searchResults->setSearchCriteria($searchCriteria); $collection = $this->slideCollectionFactory->create(); foreach ($searchCriteria->getFilterGroups() as $filterGroup) { $fields = []; $conditions = []; foreach ($filterGroup->getFilters() as $filter) { $condition = $filter->getConditionType() ? $filter->getConditionType() : 'eq'; $fields[] = $filter->getField(); $conditions[] = [$condition => $filter->getValue()]; } if ($fields) { $collection->addFieldToFilter($fields, $conditions); } } $searchResults->setTotalCount($collection->getSize()); $sortOrders = $searchCriteria->getSortOrders(); if ($sortOrders) { /** @var SortOrder $sortOrder */ foreach ($sortOrders as $sortOrder) { $collection->addOrder( $sortOrder->getField(), ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC' ); } } $collection->setCurPage($searchCriteria->getCurrentPage()); $collection->setPageSize($searchCriteria->getPageSize()); $slides = []; /** @var \Foggyline\Slider\Model\Slide $slideModel */ foreach($collection as $slideModel) { $slideData = $this->dataSlideFactory->create(); $this->dataObjectHelper->populateWithArray($slideData, $slideModel->getData(), '\Jeff\Slider\Api\Data\SlideInterface'); $slides[] = $this->dataObjectProcessor->buildOutputDataArray($slideData, '\Jeff\Slider\Api\Data\SlideInterface'); } $this->searchResultsFactory->setItems($slides); return $this->searchResultsFactory; /* Modified by Jeff on Jun 23r, 2017 $objects = []; foreach ($collection as $objectModel) { $objects[] = $objectModel; } $searchResults->setItems($objects); return $searchResults; */ } }
** At this point, our WEB REST API is created.
Step 4: Set up oAuth authoriztion
create callback-url.php
#create a fold /webroot/web-app and generate a file callback-url.php
Create identity-link-url.php
#create a file at /webroot/web-app/identity-link-url.php External Book App Login
HTML;
Create New Integration at backend at System=>Extension=>Integration as shown in following image
After you save the new Integration, you could get Consumer Key, Consumer Secret, Access Token, and Access Token Secret
Call our new WEB REST API with following code
$consumerKey, 'oauth_nonce' => md5(uniqid(rand(), true)), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => time(), 'oauth_token' => $accessToken, 'oauth_version' => '1.0', ]; $data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret); //echo $data['oauth_signature'], "\n"; $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => [ 'Authorization: OAuth ' . http_build_query($data, '', ',') ] ]); $result = curl_exec($curl); var_dump($result); curl_close($curl);
You will get the final result like:
string(43) "{"id":3,"slide_id":3,"title":"Third Slide"}"
The complete code can be downloaded at GitHub