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

Why AI WordPress Development is the Key to Business Growth in 2026

Over the past 18 months, there have been more changes in the digital ecosystem than…

3 days ago

How and Why SEO for HVAC Company Websites Strongly Outperforms Paid Ads in 2026

HVAC businesses within today's digital market need effective methods to increase their customer base and…

3 days ago

HR Software vs Manual HR: Proven Cost & ROI Benefits

Human resource management is an important aspect in determining organizational success. However, the way human…

5 days ago

Best Student Experience Apps Review: Study and Campus Productivity Tools Compared

Most “best student experience apps ” lists recycle the same picks without evidence. We set…

2 weeks ago

How Chatbot Development Is Powering Growth for SaaS Companies

Imagine late at night, you visit a SaaS website, exploring a tool that could potentially…

2 weeks ago

Core Web Vitals Optimization: The 0.1 Second Advantage That Determines Your 2026 Rankings

In 2021, when Google rolled out its Page Experience update, Core Web Vitals metrics officially…

2 weeks ago