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 Launch Your First Automated Webinar in 6 Easy Steps

Imagine hosting a webinar that runs automatically, working for you 24/7, even when you're asleep.…

2 days ago

eCommerce SEO: 4 Powerful Tips for In-House vs. Outsourcing

Pretty much every business, especially in eCommerce, has an online presence. Consumers tend to hit…

4 days ago

Magento 2 AI Voice Changer Integration: Boost Customer Engagement with This Powerful Feature

In today’s competitive e-commerce landscape, Magento 2 stores are continually evolving to meet customer expectations…

5 days ago

The Anatomy Of A Perfect Product Page: 6 Ecommerce Design Tips For 2025

If you’re reading this, you already know that your product page isn’t just a page.…

7 days ago

How Lucky Draw Plugins Help You Collect Leads And Build Brand Loyalty In 2025?

Ever heard of lucky draw plugins for WooCommerce? You will hear it more after knowing…

7 days ago

How To Use Personalization To Build Brand Loyalty In E-Commerce | 2025 Updated

In an ever changing world of e-commerce with so many options for customers, it’s quite…

1 week ago