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

7 Best Tools for Creating YouTube Videos Without Showing Your Face

The faceless YouTube channel trend has exploded in recent years. Creators are building massive audiences…

1 day ago

A Developer’s Guide to Ecommerce Development for Profitable Stores in Any Product Niche

The ecommerce boom isn't slowing down anytime soon. More businesses are moving online, and they…

2 days ago

Automation Tools for Developers in 2026: The Ultimate List for Smarter, Faster Development

The pace in the software development landscape has never been faster. The world, in turn,…

5 days ago

How to Manage Development Teams in a Growing Magento Agency

Growing Magento development agencies face increasing operational and technical complexities as teams expand rapidly. Multiple…

1 week ago

How Modern Businesses Can Transform Supply Chain Communication at Scale

The way companies exchange data with their trading partners can make or break operational efficiency.…

2 weeks ago

How Developers Can Master Modern Website Protection Without Losing Momentum

Modern websites are built to be fast, dynamic, and secure. At the same time, developers,…

2 weeks ago