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

WooCommerce vs Shopify Plus: Which Platform Scales Better for Growing Businesses?

E-commerce businesses constantly evolve, and growth often exposes issues that were not visible earlier. A…

2 days ago

Rewriting eCommerce Content for Scalable Growth in the AI Era

eCommerce Content has become a critical growth driver in today’s highly competitive, AI-driven digital marketplace.…

5 days ago

Powerful AI Tools That Are Transforming How Developers Handle Documentation

Documentation remains one of the biggest challenges in modern software development. Every developer knows the…

6 days ago

Why Web Design and Web Development Are Critical for Business Growth and Success

Websites are the cornerstone of any modern enterprise because they are the primary means by…

1 week ago

How Rule Fatigue Silently Destroys Ecommerce and Causes Account Failures in Prop Trading

Not all e-commerce businesses fail dramatically. Many don’t collapse due to a single major mistake,…

2 weeks ago

Power Up E-commerce Growth with Custom AI Development Studios in 2026

AI Development Studio solutions are rapidly becoming a core driver of modern e-commerce success. Online…

2 weeks ago