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

12 Best Custom Software Development Companies for Scalable EdTech Platforms in 2026

Compare 12 custom software development companies with proven EdTech delivery, from LMS migrations to AI-powered…

2 weeks ago

7 Best Microsoft Dynamics 365 Implementation Partners for Manufacturing

Factories everywhere are running a tighter game. Post-2023 supply-chain whiplash, relentless cost pressure, and a…

3 months ago

Ecommerce Web Development Approaches: How to Pick the Right One

Picture this: a business rushes into a platform decision based on what a competitor was…

4 months ago

How AI-First Engineering Is Driving Incredible Innovation in Custom Software Development

The software development landscape has changed at an accelerated rate in the last ten years,…

4 months ago

How Website Architecture and Page Speed Boost eCommerce Conversion Rates

Imagine walking into a store where the aisles are a maze, the lighting is dim,…

4 months ago

Why Product Videos Are Essential for a Better Online Shopping Experience

Product videos have become one of the most effective tools for helping online shoppers make…

4 months ago