How to create custom API in Magento 2

Published On: 11 July 2018.By .
  • Digital Engineering
  • Ecommerce

The REST API documentation published on the Magento 2 Developer Documentation website describes the REST APIs that are available on the latest release of Magento 2.  This documentation is generated from the code base using Swagger and represents the state of the code at the time the documentation was generated. Swagger displays a list of service names. Click on a service name to display the list of APIs defined within that service. Click on an API name to display detailed information about that API.

You can also create a dynamic REST API documentation set on your server with live data. On your server, Swagger displays REST APIs for all installed products and allows you to try out the APIs. For more information, see Generate local REST API reference.

Magento 2.x Apis:  http://devdocs.magento.com/swagger/index.html

Now you can follow following steps to create custom API in magento 2.

Access API with Rest Method:

Step 1  System =>  Integrations => Add Integration

Step 2  System => User Roles => Add New Role

After creating this access for access authorise resource. Now lets create an API. Create Api process similar as Create custom module in magento.

For Ex, we will create a Login API Step By Step.

API Module Structure.

File Details

       1. registration.php

               “Registration.php” file required in installation process Magento 2.

                     Here we create a Sample Module for Mobile Api which name “Auriga_Mobileapp” Auriga is vendor name and Mobileapp is module.

2. module.xml

Module.xml which tells magento about our module.Here we declare Module Name and Version control.

Here we explain sample module Auriga_Mobileapp which Version 2.0.0

3. Webapi.xml

If you wants to create a method which calls through api must be declared in webapi.xml.

Here I create login method for Sample Example.

For Ex.

url=”MAGENTOROOT/V1/api/customer/login”

method=”POST”

ref=”anonymous”

Url which tell the path of access api Method pass the parameters inside api Ref  declaration who can access method (No need to authorization).

As Sample Request

 

4. di.xml

Basically di.xml using Overriding core module.

Here we declare Login Method in CustomerInterface  And define in Customer model.

5. CustomerInterface.php

Declaration of our method Sample Method here we declare our method.

6. Customer.php

Definition of our method.

Now we can access our login method by :

curl -d ‘{“email”:”XXX@aurigait.com“,”password”:”xxxx”}’ -H ‘Content-Type: application/json’ ROOT/rest/V1/api/customer/login

Related content

That’s all for this blog

Go to Top