Magento 2 API are used to fetch the data and create or update data in magento.
Following is the example of creating custom api for GET and POST
In Magento 2, a module is developed with service contract design pattern, the RepositoryInterface is used for
API GET and POST to get the records and save the record respectively.
Refer the webapi.xml in the etc folder of CMS module
However, the custom API can be implemented by customizing the RepositoryInterface or creating new Interface
The new interface should be created with '@api' anotation.
Eg:
/**
* @api
*/
interface StoneManagementInterface
{
/**
* Get Terms and Conditions.
*
* @return \Zend\Json\Json
*/
public function getTermsAndConditions();
/**
* Get Rate list.
*
* @return RateSearchResultsInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getRates();
}
The first method is just return as the Json but the second method use the class that extends Magento\Framework\Api\SearchResultsInterface;
in the service contract implementation.
/**
* Get the term and conditions.
*
* @return array
*/
public function getTermsAndConditions()
{
return [
'update_at' => '2022-01-06',
'version' => 1,
'content' => '<h1>The terms and conditions</h1><p> The conditions </p>',
'is_accepted' => 0
];
}
/**
* @inheritdoc
*/
public function getRates()
{
$params = $this->request->getParams();
$adminId = (should be fetched from admin token)
if (!$adminId) {
throw new LocalizedException(__('Not authorized to get Rates. '));
}
return $this->rateRepository->getList($this->service->getRatesearchCriteria($adminId, $params));
}
In the webapi.xml file
<route url="V1/bidding/termsandconditions" method="GET">
<service class="Vasan\Bidding\Api\MilestoneManagementInterface" method="getTermsAndConditions"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
<route url="V1/bidding/rates" method="GET">
<service class="Vasan\Bidding\Api\MilestoneManagementInterface" method="getRates"/>
<resources>
<resource ref="Vasan_Bidding::rate_get"/>
</resources>
</route>
Posted by vasan to vasan's deck (2021-09-24 12:01)