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

15+ Must-have Magento 2 Free Extensions To Supercharge Your Store In 2025 | Latest updates

Magento 2 is an incredibly flexible and powerful eCommerce platform that can be tailored to…

7 days ago

Black Friday 2024: Hot Deals Collection For Magento 2

Black Friday and Cyber Monday – BFCM 2024 are nearly around the corner, and it’s…

1 week ago

What To Consider While Using Magento 2.0 For Your Streaming App?

When it comes to e-Commerce platforms, undoubtedly Magento 2.0 grabs the spotlight. Magento might not…

1 week ago

Landofcoder BFCM 2024: Biggest Sale Of The Year – 30% OFF All Magento 2 Extensions

The holiday shopping season is here, and there’s no better time to supercharge your Magento…

2 weeks ago

Top 10 Progressive Web App Development Companies To Elevate Your Business

In today’s digital landscape, the rapid evolution of advanced web applications, particularly Progressive Web Apps…

2 weeks ago

Why Your Retail Business Needs Big Data eCommerce In 2025?

As eCommerce booms, big data eCommerce will be all about providing insight into how to…

2 weeks ago