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

How SaaS-Based Magento Extensions Can Dramatically Supercharge Your Store in 2025?

Having your Magento store up and running requires more than having a good platform when…

3 days ago

Top 4 Reliable Managed IT Services in Boston to Empower Your Business

Running a business today isn’t easy. Technology problems can slow you down and leave your…

3 days ago

WooCommerce or Magento? A Business Owner’s Guide to Choosing the Best Platform in 2025

Everyone with a strong exposure to online stores and eCommerce are very aware about platforms…

4 days ago

How To Reduce Cart Abandonment And Increase Sales In Your Online Store In 2025

Have you witnessed your clients placing items into their shopping cart, only for them to…

2 weeks ago

AI vs Traditional B2B eCommerce: Top 10 Powerful Platforms Leading the Digital Transformation

In the global business arena, AI vs Traditional B2B eCommerce has altered how businesses interact,…

3 weeks ago

Top 7 SEO Tools Every Magento Store Owner Should Use in 2025

As an ecommerce business owner, it would be a dream to see thousands of interested…

4 weeks ago