Today we are going to learn how to create rest based api in magento2. I have worked on magento1 and found it very difficult to create a rest webapi, but as I was expecting magento2 has a very easy way to define your api resources for the module, specially defining routes.
In order to create a rest api there are some certain requirements :
- you need to create an interface in your modules Api folder.
- then you need to define all the api methods that you want to expose to the web in the interface.
- All the methods should have a doc-block.
- in the doc-block @api must be defined
- if your method expects parameters than all the parameters must be defined in the doc-block as @params <type> <param> <description>
- return type of the method must be defined as @return <type> <description>
- concrete class of the method must be defined and it should give the definition of all the api methods and should inherit the doc-block.
If your api method do not met any of the above requirements then rest api will not work .
Now for an example lets create a test module named Webkul_TestApi for better understanding :
create your module composer.json, registration.php and module.xml files: