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

How a SaaS SEO Consultant Can Transform Your Growth Strategy

En a digital-first economy, Software-as-a-Service (SaaS) businesses need to be visible. Without visibility, even the…

22 hours ago

Embracing the Cloud | Powerful Advantages of Leveraging Cloud Servers in 2025

After all, in business we're living by a binary decision. As the world becomes more…

1 day ago

Top 7 Emerging Programming Languages Developers Should Learn

In a world where technology evolves rapidly, developers who stay ahead of the curve gain…

2 days ago

Top Website Development Trends Every PPC Expert Swears By in 2025

The digital world is constantly changing and this way together website development and PPC advertising…

2 days ago

From Factory Floor to Online Store: How Manufacturers Can Leverage eCommerce to Boost Growth

Manufacturing is changing fast. Buyers want direct access to products, quick fulfillment, and reliable updates.…

4 days ago

Top 10 Powerful Magento 2 Extensions to Maximize ROI in 2026

The eCommerce industry is competitive. Business owners need to explore all possible ways to enjoy…

1 week ago