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

E-Commerce Shipping Tips for 2025: Save More, Ship Smarter

Shipping costs can reduce your profits really fast when you are selling on the web.…

2 days ago

12 Best Practices for Optimizing User Experience in 2025

You don’t always notice a great user experience. But you always feel when it’s missing. …

4 days ago

5 Key Principles for a Successful AWS Cloud Native Architecture Strategy

AWS cloud native architecture strategy is becoming increasingly important for businesses that want scalable, resilient,…

1 week ago

10 Powerful Ways Web Development Boosts User Experience & Conversion Rate

Your site does more than simply exist on the internet—it frequently is the initial contact…

2 weeks ago

5 Powerful AI Teams Behind the Most Realistic Digital Avatars Online

Creating a digital version of a human face that talks, moves, and feels real isn’t…

2 weeks ago

9 Powerful Magento Extensions to Dramatically Boost Store Performance

With so many options to choose from, finding the right Magento extensions to boost store…

2 weeks ago