API stands for Application Programming Interface to allow you access the data from an application. API can be called as a middleman between a programmer and an application. When the programmer calls for a request via the middleman, if the request is approved, the right data will be turned back.
Follow the below steps to create APIs
Web API configuration
In webapi.xml we are configuring access rights and API Interface that specified method will use.
File : app/code/PHPCodez/First/etc/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 method="GET" url="/V1/phpcodez-first/post"> <service class="PHPCodez\First\Api\PostManagementInterface" method="getPost"/> <resources> <resource ref="anonymous"/> </resources> </route> </routes>
Define Interface – etc/di.xml
File : app/code/PHPCodez/First/etc/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="PHPCodez\First\Api\PostManagementInterface" type="PHPCodez\First\Model\PostManagement"/> </config>
In di.xml we define what model will interface call to. We also need to add Interface and Model, please note that you need to take care about comments also.
Interface – Api/PostManagementInterface.php
<?php namespace PHPCodez\First\Api; interface PostManagementInterface { public function getPost($param); }
Model Model/PostManagement.php
<?php namespace PHPCodez\First\Model; class PostManagement { public function getPost($param) { return 'You have passed the parameter ' . $param; } }
Issue the following comands
php bin/magento setup:upgrade php bin/magento setup:static-content:deploy -f php bin/magento cache:clean
Load the following URL
http://127.0.0.1/mage2/rest/V1/phpcodez-first/post?param=phpcodez
And you can see the reponse like <response>You have passed the parameter phpcodez</response>