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

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 days 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…

2 weeks 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,…

2 weeks 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,…

2 weeks 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…

2 weeks ago

Proven Guide to Scalable Software Development Services for Startups

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

3 weeks ago