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 To Prevent Data Breaches Risks In Integration And Third-Party Apps | 2025 Updated

Due to the ever-increasing reliance of businesses on third-party apps and integrations to complete processes…

1 day ago

Best Website Design Practices For Restaurants | 2025 Updated

Your website is a visual representation of your restaurant. It acts as a welcome mat…

1 day ago

Custom SaaS Development vs. No-Code Platforms: The Ultimate Guide to Making the Right Choice in 2025

The availability of no-code tools has made software development more accessible than ever before. Businesses…

2 days ago

How To Get More Organic Traffic? Best 5 Tips For Your E-Commerce Website

Starting an e-commerce brand is not always a matter of building a powerful product. Your…

2 days ago

Generative AI for E-Commerce Business: Powerful Trends You Can’t Ignore in 2025

Generative artificial intelligence (AI) represents an exciting new frontier in technology with huge potential to…

2 days ago

4 Powerful Ways AI Meeting Managers Help Teams Organized and on Track

Without proper organization, meetings can become a drain on productivity, leading to missed deadlines, forgotten…

3 days ago