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

WooCommerce Measurement Price Calculator: Smart Pricing Made Easy in 2025

Ever felt like your online store is losing sales just because your pricing doesn’t fit…

2 days ago

The Ultimate SEO Outsourcing Strategy for 2025: Scale Your Business Smarter

You’ve probably heard the phrase ‘Just outsource it’ around the business circles like a life-saving…

2 days ago

PrestaShop Auction Module for Better Sales and Customer Engagement 2025

Customers on the internet aren't content with static product descriptions and once-off price lists. A…

3 days ago

7 Powerful Benefits of DevOps for Mobile App Development Beginners Should Know

In today’s fast-paced digital landscape, delivering mobile apps that are fast, reliable, and secure is…

4 days ago

9 Proven Tips for a Smooth and Successful eCommerce Store Migration

Your online store is growing, but your platform isn't. That slow checkout process, those missing…

1 week ago

5 Proven Strategies High-Performing Websites Use to Master User Flow

High-performing websites look appealing and help users navigate through content with intent. Many websites look…

1 week ago