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

6 Smart Strategies High-Performing Brands Use to Succeed in a Digital Marketing Campaign

Today’s digital landscape is more dynamic and competitive than ever, with countless brands trying to…

4 days ago

Audioenhancer.ai Review: A Must‑Have for Content Creators? | 2025 Guide with Top Features

Audioenhancer.ai Review: High‑quality audio makes videos, podcasts, and voice‑overs sound professional and keeps listeners engaged.…

5 days ago

7 WooCommerce Menu Cart Features That Boost Sales and Improve Checkout

Running an online store takes more than just having nice products because the way your…

5 days ago

10 Ways Tech Candidates Can Make Their Strengths Obvious to Hiring Managers

Can Make Their Strengths Obvious – this is what every tech candidate and developer must…

5 days ago

Why WooCommerce Testing Is Crucial for eCommerce Success in 2025

In the fast-paced world of eCommerce, ensuring your online store operates seamlessly is no longer…

1 week ago

Building Scalable Music Streaming Apps with PWA and Magento Integrations for 10x Growth

Music streaming is more than just about playing songs; it's more about sharing a better…

2 weeks ago