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

Uncovering the True Cost of Managed Service Providers as Businesses Scale

The True Cost of Managed Service Providers often goes far beyond monthly invoices. As businesses…

2 hours ago

Uncovering the Hidden True Cost of Cloud Infrastructure for Legacy-Dependent Businesses

Cloud infrastructure is transforming enterprise IT strategies, but for legacy-dependent businesses, the journey is far…

3 hours ago

Unseen Cybersecurity Threats in Cloud-Powered Remote Work Environments

As organizations increasingly rely on cloud infrastructure to power distributed workforces, hidden cybersecurity vulnerabilities are…

4 hours ago

From Tattoo Flash Art to Online Store Success: eCommerce Trends Shaping Creative Businesses

You have a photo that you are in love with, maybe it is a sunset…

4 hours ago

How AI Is Transforming MSP Cybersecurity in a Rapidly Evolving Threat Landscape

In today’s fast-paced digital environment, Managed Service Providers (MSPs) are at the forefront of protecting…

10 hours ago

How Can You Speed Up Your Hardware Prototyping Phase Without Sacrificing Quality?

Honestly speaking, hardware prototyping could be like a tightrope walk. On the one hand, there…

11 hours ago