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

Best Student Experience Apps Review: Study and Campus Productivity Tools Compared

Most “best student experience apps ” lists recycle the same picks without evidence. We set…

4 days ago

How Chatbot Development Is Powering Growth for SaaS Companies

Imagine late at night, you visit a SaaS website, exploring a tool that could potentially…

5 days ago

Core Web Vitals Optimization: The 0.1 Second Advantage That Determines Your 2026 Rankings

In 2021, when Google rolled out its Page Experience update, Core Web Vitals metrics officially…

5 days ago

The Shocking Impact of Google’s AI Search (SGE) on Organic Traffic Strategies in 2026

For over 20 years, organic search was built on a simple premise: Rank higher on the…

1 week ago

How to Humanize AI Content for Magento Blog Posts and Product Pages Effectively

Humanize AI content is now a critical step in modern eCommerce workflows. AI writing tools…

1 week ago

Key Benefits of Multi-Vendor Marketplace Software for Modern Businesses

The digital economy has caused substantial changes in how businesses function. Numerous businesses are moving…

2 weeks ago