How to Create Custom API in Magento 2

November 24, 2016 / Posted in Magento, Magento 2, Most Popular by Andrey Matveev
How to Create Custom API in Magento 2
Download PDF

Today I’d like to guide you through the process of creating Custom API in Magento 2.

At first we must create the primary files of a module.

composer.json:

registration.php:

etc/module.xml:

The second step is – create an interface for custom API. Let’s create Api/TestInterface.php file and save it with the following content:

That’s how we created an interface with the following functions:

test() function, it doesn’t receive any parameters;

test1($param), it does receive 1 parameter in order of the call to our API.

Now we must create a model, that would work through our interface. Let’s create Model/Test.php file and write the following code into it:

We have just created a model, which is inherited by our interface and we described functions that are called in it. After that we must connect our interface with the model. Please do the following to perform it:

Create etc/di.xml file with the following content:

Then we create a path to call our API. For that we write the following in etc/webapi.xml file:

Here we specified 2 paths to our functions:

/V1/test/ , which calls test method in TestInterface
/V1/test1/:param, which calls test1 method in TestInterface, receives parameter and transfers it into function.

API is called through the GET method, but you can change it to POST, DELETE or some other methods, if you want.

Also you are able to specify users group, that have permission to call your API or you can specify your own rule through the following structure, which is described in <route></route>:

And it’s possible to indicate Magento_Customer::group, self, Magento_Customer::admin and other rules, instead of anonymous.

It is possible to indicate additional parameters as well. For example we need to transfer customer_id parameter into the function through the interface.

For that purpose we will write the following between <route></route>:

Thus we should add a parameter in our interface and and model, which will receive customer_id value.

Api/TestInterface.php:

Model/Test.php:

That’s all. We’ve just created custom API and now it’s ready to use.



Post a new comment