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 10 Trusted Web App Development Companies to Elevate Your Digital Strategy

In today’s digital landscape, the rapid evolution of advanced web applications, particularly Progressive Web Apps…

7 hours ago

Why Your Retail Business Needs Big Data eCommerce In 2025?

As eCommerce booms, big data eCommerce will be all about providing insight into how to…

9 hours ago

The Best Role Of Magento 2 In Shaping The Future Of Ecommerce

The ecommerce industry is booming like never before. In fact, global retail ecommerce sales are…

1 day ago

13 Best Practices For Developing Custom WordPress Solutions

From brick-and-mortar retail to SaaS, a robust online presence is vital for business success. A…

3 days ago

AML Compliance In E-commerce: Why It’s Essential For Fraud Prevention?

In the e-commerce world, complying with Anti-Money Laundering (AML) regulations is more important than you…

7 days ago

How to Optimize Your Magento Store’s Marketing Strategy

Magento is the 4th most popular eCommerce platform used globally, and optimizing the marketing strategy…

1 week ago