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

Proven Guide to Scalable Software Development Services for Startups

Startups today operate in an environment where speed and adaptability and scalability determine their ability…

16 hours ago

Ultimate Education App Development Cost Breakdown: Features, Tech Stack & Timeline

The education industry has gone through a pretty massive digital transformation over the past few…

19 hours ago

Successful How to Integrate GenAI Agents into Your Website: A Developer’s Practical Guide

Visitors are no longer satisfied with static FAQ pages or chatbots. They want quick and…

2 days ago

Effective Liquor Store Website Design: How to Turn Visitors into Buyers

In today's digital marketplace having an online presence for retail businesses is no longer just…

2 days ago

What Do DevOps Service Providers Actually Deliver? A Complete DevOps Services Breakdown in 2026

"DevOps is not a goal, but a never-ending process of continual improvement." — Jez Humble,…

2 days ago

WooCommerce Open Pricing Guide: Set Minimum & Recommended User Prices

WooCommerce Open Pricing gives store owners a powerful way to let customers enter their own…

2 days ago