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

Top 5 Magento Extensions for Seamless Recurring Payments

Suppose you are an e-commerce business owner or a service provider. In that case, the…

1 hour ago

The Complete Guide To Magento Website Development Process

Magento website development can be chaotic and complex. When you least expect it, complexities can…

2 hours ago

Smooth and Secure Database Migration Services for Your Business

Effective data management is crucial for a company's success in today's business environment. Data plays…

7 days ago

Magento 2 PWA: Optimizing Performance with a Global DNS Strategy

Magento 2 is one of the most popular open-source e-commerce website builders available today. It…

1 week ago

The Secrets To High Converting Shopify Product Pages

If your business has struggled to hit sales goals on your Shopify store, you’re not…

2 weeks ago

Improve eCommerce Business Brand Image – Best Marketing Tips For 2024

Branding is such a commonly used word in marketing. However, many people overlook and understand…

4 weeks ago