![API](https://landofcoder.b-cdn.net/wp-content/uploads/2022/03/feature-create.png)
Table of Contents
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:
![begin](https://landofcoder.b-cdn.net/wp-content/uploads/2022/03/1.png)
Firstly, we must define the API in etc/webapi.xml as below:
![first](https://landofcoder.b-cdn.net/wp-content/uploads/2022/03/2-3.png)
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:
![next step](https://landofcoder.b-cdn.net/wp-content/uploads/2022/03/3-3.png)
The Mode/firstApi.php has the below content:
![custom](https://landofcoder.b-cdn.net/wp-content/uploads/2022/03/4-5.png)
Finally, we need to create a preference at etc/di.xml as follow:
![custom API](https://landofcoder.b-cdn.net/wp-content/uploads/2022/03/5.png)
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
![API custom](https://landofcoder.b-cdn.net/wp-content/uploads/2022/03/7.png)
The results response:
![](https://landofcoder.b-cdn.net/wp-content/uploads/2022/03/image2-1024x446.png)
Good luck to you!
Read more: