DEV Community

Lao Ning
Lao Ning

Posted on

How to Create a Custom Magento 2 API?

Magento 2 is a robust e-commerce platform with extensive API support. While it offers default REST APIs, you might need to create a custom REST API. This article explores the process of creating a custom REST API in Magento 2.

What is a Magento 2 Custom REST API?

A Custom REST API in Magento 2 is a web service endpoint you create for specific actions or data retrieval from your Magento store. Custom APIs are tailored to your business needs. They integrate Magento with external systems, mobile apps, or other software applications. Custom APIs are crucial when default APIs do not cover certain functionalities or data needs.

Scenarios for Creating a Custom REST API in Magento 2:

  • Integrating with Third-party Systems: Custom APIs allow data exchange with external platforms like ERP systems, CRM software, or payment gateways.
  • Building Mobile Apps: These APIs are essential for mobile apps that need interaction with your Magento store.
  • Implementing Unique Features: Custom APIs enable features like unique loyalty programs or personalized product recommendation engines.

Steps to Create a Custom Magento 2 REST API:

Step 1: Set Up Your Development Environment

Ensure that you have a development environment with Magento 2 installed. You'll also need a code editor and a REST client for testing.

Step 2: Define Your API Endpoints

Determine the functionality you want to expose. For this example, let's create an API to retrieve product details by SKU.

Step 3: Create a Module

Create a custom module for your API. Replace Vendor and Module with your own module and namespace names.

Create app/code/Vendor/Module/etc/module.xml with the following content:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="1.0.0" />
</config>
Enter fullscreen mode Exit fullscreen mode

Create app/code/Vendor/Module/registration.php with the following content:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
);

Enter fullscreen mode Exit fullscreen mode

Step 4: Create a Web API Schema
Create a webapi.xml file to define the API endpoint.

Create app/code/Vendor/Module/etc/webapi.xml with the following content:

<?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/custom/product/:sku">
        <service class="Vendor\Module\Api\ProductInterface" method="getProductBySku"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>
Enter fullscreen mode Exit fullscreen mode

Step 5: Create a Di.xml File

Create a di.xml file to specify the implementation of your API interface.

Create app/code/Vendor/Module/etc/di.xml with the following content:

<?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="Vendor\Module\Api\ProductInterface" type="Vendor\Module\Model\Product"/>
</config>

Enter fullscreen mode Exit fullscreen mode

Step 6: Create the API Interface

Create an interface for your API. This defines the methods your API will expose.

Create app/code/Vendor/Module/Api/ProductInterface.php with the following content:

<?php
namespace Vendor\Module\Api;

interface ProductInterface
{
    /**
     * Retrieve product details by SKU
     *
     * @param string $sku
     * @return \Vendor\Module\Api\Data\ProductInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException If product with the specified SKU doesn't exist.
     */
    public function getProductBySku($sku);
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Implement the API Interface

Create the implementation of your API interface.

Create app/code/Vendor/Module/Model/Product.php with the following content:

<?php
namespace Vendor\Module\Model;

use Vendor\Module\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class Product implements ProductInterface
{
    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    public function __construct(
        ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function getProductBySku($sku)
    {
        try {
            $product = $this->productRepository->get($sku);
            return $product;
        } catch (NoSuchEntityException $e) {
            throw new NoSuchEntityException(__('Product with SKU %1 not found.', $sku));
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 8: Test Your Custom API
You can now test your custom API using a REST client like Postman. Make a GET request to the following endpoint:

[YourMagentoURL]/rest/V1/custom/product/{SKU}
Enter fullscreen mode Exit fullscreen mode

Replace {SKU} with the SKU of the product you want to retrieve. You should receive a JSON response with the product details.

Note: This post was referenced from https://meetanshi.com/blog/create-custom-rest-api-in-magento-2/. It may contain excerpts from the original author.

If you have any questions or need further clarification, please feel free to leave a comment.

Top comments (0)