Magento 2 Create API

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="" 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"/>
 <resource ref="anonymous"/>

Define Interface – etc/di.xml

File : app/code/PHPCodez/First/etc/di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 <preference for="PHPCodez\First\Api\PostManagementInterface" type="PHPCodez\First\Model\PostManagement"/>

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

 namespace PHPCodez\First\Api;
 interface PostManagementInterface {
 public function getPost($param);

Model Model/PostManagement.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

And you can see the reponse like <response>You have passed the parameter phpcodez</response>

Leave a Reply

Your email address will not be published. Required fields are marked *