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

20 Proven Ways to Dramatically Speed Up WooCommerce Orders for Returning Customers and Bulk Buyers

Ever watch a customer hesitate? That tiny pause. That moment when they look at the…

2 days ago

The Modular Mindset: How Modular Magento Architecture Drives Unstoppable Performance

Modular Magento architecture rarely fails loudly. Most of the time, a poor setup just slows down.…

3 days ago

Best Link Building Agencies Powering SEO Growth in 2026

The links that are posted are not ordinary links; they are the ballots of approval…

6 days ago

What Modern Retailers Need in a Powerful Returns Management Platform

Returns complexity has exploded. You're managing omnichannel returns, multiple warehouse locations, and seasonal spikes. Managing…

2 weeks ago

How to Improve User Experience with Effective Mobile App Testing?

Mobile applications have already been our go-to savior for streamlining our daily lives. So, in…

2 weeks ago

6 Best AI Pitch Deck Creators for Ecommerce Startups

AI pitch deck creators for e-commerce startups are transforming how founders prepare investor presentations. Building…

2 weeks ago