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

Top BI Trends in 2025 Every Data-Driven Leader Should Know

BI Trends in 2025 — Every business is driven by data, and they use data…

1 day ago

Why Magento 2 Integration Boosts Umbraco Development Efficiency

The pandemic brought a huge difference in consumer behavior, digital adoption, and online sales rate.…

5 days ago

The Essential Guide to Optimize Website Layouts for Superior Speed

To optimize website layouts effectively is one of the most crucial steps in enhancing site…

1 week ago

The Importance of SEO Services for Manufacturers: Driving Online Success in a Competitive Industry

In the manufacturing industry, staying ahead of the competition is essential for long-term success. As…

1 week ago

The Business Impact of Skipping Mobile Performance Testing in 2026

In the current virtual world, mobile apps have become a crucial part of our daily…

1 week ago

Why Strapi CMS Is the Best Choice for Magento 2 Headless Projects

Strapi CMS for Magento 2 Headless Projects is transforming how e-commerce owners manage complex content…

1 week ago