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

Building Scalable and Efficient Call Centers with AI Software Solutions

Customer support has become more critical to business success than ever before in today’s fast-paced…

21 hours ago

6 Powerful WooCommerce Deposit Tools That Boost Conversions

WooCommerce Deposit Tools play a critical role in helping online stores reduce cart abandonment and…

2 days ago

20 Proven Ways to Dramatically Speed Up WooCommerce Orders for Returning Customers and Bulk Buyers

Ever watch a customer hesitate? That tiny pause. That moment when they look at the…

6 days ago

The Modular Mindset: How Modular Magento Architecture Drives Unstoppable Performance

Modular Magento architecture rarely fails loudly. Most of the time, a poor setup just slows down.…

7 days ago

Best Link Building Agencies Powering SEO Growth in 2026

The links that are posted are not ordinary links; they are the ballots of approval…

1 week ago

What Modern Retailers Need in a Powerful Returns Management Platform

Returns complexity has exploded. You're managing omnichannel returns, multiple warehouse locations, and seasonal spikes. Managing…

2 weeks ago