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

Why Is Testing Critical For E-commerce Applications?

E-commerce has changed the way we shop and conduct business. Today, most people prefer to…

2 days ago

AI Schema Generator: 10 Proven Ways to Dramatically Improve Your SEO

AI schema generator tools make it easier to implement structured data markup on a website by…

1 week ago

What Defines an Elite 3D Animation Company in Gaming: The Ultimate Standards of Excellence

Animation brings games to life. It turns still models into characters players care about and…

1 week ago

Unveiling the Invisible: The Hidden Risks and Costs in MSP Service Models Amid Rapid Growth

Hidden Costs in MSP Service Models are often overlooked during contract negotiations, yet they can…

1 week ago

Unveiling the Invisible: Mastering MSP Service Models Amid Evolving Cyber Threats

MSP Service Models are becoming increasingly critical as organizations navigate an era of evolving and…

1 week ago

The Hidden Cybersecurity Risks of Cost-Effective MSP Service Models

Cost-Effective MSP Service Models are increasingly popular among businesses seeking to reduce IT expenses while…

1 week ago