Categories: Magento News

How to create a custom API in Magento 2

I. Application Programming Interface

API (Application Programming Interface) is an extremely important part of systems in general and Magento 2 in particular. We will learn the way to create a custom API in Magento 2.

We need a tool to interact with the API, we will use Postman, one of the most popular tools.

You can try to Download

II. The way to create a custom API in Magento 2

First of all, we will create a new module with the following directory structure:

Firstly, we must define the API in etc/webapi.xml as below:

In there:

  • Route:
    + method: the way to get data, can be GET or POST
    + URL: Link address
  • Service:
    + class: link of the handler class
    + method: which method to handle this request
  • Method

Next, we need to create an interface class  as Api/FirstApiInterface.php:

The Mode/firstApi.php has the below content:

Finally, we need to create a preference at etc/di.xml as follow: 

We need to run the following commands for the module to work: 

  • bin/magento setup:upgrade
  • bin/magento setup:di:compile
  • bin/magento cache:flush

To verify the result, we create a request in Postman with its URL: 

https://localhost/rest/all/V1/landofcode-firstapi/hello?name=LandofCode

The results response: 

Good luck to you!

Read more:

Joe Kun

Recent Posts

Top 5 Best Amazon Repricers with Inventory Management Integration for Maximum Profits

Amazon repricers with inventory management integration are essential tools for sellers who want to stay…

5 days ago

7 Powerful Ways Humanized AI Product Descriptions Boost Magento Store Conversions

Shoppers want language that feels natural, stirs curiosity, and helps them imagine how a product…

1 week ago

10 Best AI Software Development Companies to Watch in 2025

This article highlights the topmost AI software development companies redefining the AI landscape in 2025.…

2 weeks ago

Beyond the Plugin: Building Powerful Next-Generation B2B eCommerce With AI

For a long time, B2B eCommerce meant clunky interfaces and static catalogs. Businesses relied on…

2 weeks ago

Data-Driven Personalization Magento: How AI Dramatically Enhances Extensions

Generic online stores fail to convert visitors. They offer the same experience to every individual.…

3 weeks ago

Top 10 Extensions Every SEO Expert Must Use in 2025

If you’ve been in the SEO game for more than five minutes, you know one…

3 weeks ago