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

Vanta vs Drata: A Critical Practical Guide to Choosing Compliance Automation

Vanta vs Drata — According to Cybersecurity Ventures, global cybercrime is set to cost $10.5…

20 hours ago

Essential Salesforce Cybersecurity Threats 2025: Critical Risks Every Admin Must Prepare For

Salesforce cybersecurity threats 2025 are becoming more advanced as cybercriminals increasingly target CRM platforms that…

1 day ago

Role of Custom Web Design for Business Growth in 2026

Custom web design for business growth is essential in today’s highly competitive and fast-paced digital…

2 days ago

7 Essential Software Development Models That Empower Modern Engineering Teams

Software Development Models have evolved dramatically as technology and user expectations continue to grow. These…

5 days ago

Top Travel App Trends for 2026: What Guests Truly Want for an Exceptional Experienc

Travel​‍​‌‍​‍‌​‍​‌‍​‍‌ apps are the new-age way of breaking down the travel hard work people used…

1 week ago

Scaling eCommerce Customer Support with Murf Falcon Low-Latency Voice API

In today’s eCommerce landscape, customer support defines brand loyalty. Shoppers expect instant, personalized, and multilingual…

1 week ago