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

The Future of E-Commerce: 4 Powerful Benefits of Decentralized Payment Systems

Now that the global e-commerce sector has taken off in earnest, there’s an even greater…

2 days ago

How Fintech Is Empowering Investing: 7 Smarter Tools Al Sollami Recommends for Safer Portfolios

In the fast-moving world of digital finance, fintech has gone from a buzzword to a…

2 days ago

PathSocial’s Impact: Enhancing eCommerce Platforms with Social Media Growth Tools in 2025

The success of eCommerce companies relies heavily on social media platforms which let them attract…

2 days ago

7 Powerful Tips to Choose a Salesforce Custom App Development Company for Your Business

In today's highly digital world, the rivalry between companies is getting fiercer, as is their…

2 days ago

Revolutionizing Online Reservations: Powerful Ways AI-Powered Booking Transforms E-Commerce in 2025

You know that feeling when you’re trying to book something online, and it’s a total…

4 days ago

5 Essential Steps to Build an Appealing Online Storefront for Your Startup

The recent global e-commerce boom has made the industry an appealing arena for new entrepreneurs…

4 days ago