Magento 2 Create API with samples - Snippet

Magento 2 Create API involves helping online retailers create an Application Programming Interface for personal usage. The API is a collection of protocols, routines, and other tools to design software applications. Therefore, API is a necessary element to connect the data if you request every program or service from other websites. With the creation of API in Magento 2, you can simply get all the building blocks to start a program successfully.

What is API in Magento 2?

API stands for Application Programming Interface to allow you to access the data from an application. API can be called a middleman between a programmer and an application. When the programmer calls for a request via the middleman, the right data will be turned back if the request is approved.

As eCommerce stores basing on Magento 2 platform, you should see two architectural sorts of web APIs: REST (Representational State Transfer) and SOAP (Simple Object Access Protocol). But, in the official documentation, they simply come with raw curl call without. To join and use Magento 2 API efficiently, this topic will show you PHP examples in specific.

Snippet API

File path:

 etc/webapi.xml

Code:

<?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/mageplaza-helloworld/post">

<service class="VendorName\ModuleName\Api\PostManagementInterface" method="getPost"/>

<resources>

<resource ref="anonymous"/>

</resources>

</route>

</routes>

File path:

etc/di.xml

Code:

<?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="VendorName\ModuleName\Api\PostManagementInterface" type="VendorName\ModuleName\Model\PostManagement"/>

</config>

File path:

Model/PostManagement.php

Code:

<?php 

namespace VendorName\ModuleName\Model;

class PostManagement {

/**

* {@inheritdoc}

*/

public function getPost($param)

{

return 'api GET return the $param ' . $param;

}

}

File path:

Api/PostManagementInterface,php

Code:

<?php 

namespace VendorName\ModuleName\Api;

interface PostManagementInterface {

/**

* GET for Post api

* @param string $param

* @return string

*/

public function getPost($param);

}

If you are looking for Magento 2 Developers, visit Magento 2 Services.