Redeem Now
Read More
Read now
Menu Close
    Start a Project Request quote Reading list Switch to dark mode

    How to create rest based web api in magento2


    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:

    Now create TestApiManagementInterface.php file in app/code/Webkul/TestApi/Api/ folder:


    the above will define all the api methods you want to expose, all these methods must have doc-block defined with @api, @params and @return else it will not work.


    Now create TestApiManagementInterface implementation file in app/code/Webkul/TestApi/Model/Api folder:


    the above class is the implementation of the interface as you can see I have only created one method getApiData as it is defined in the interface its return type is \Webkul\TestApi\Api\Data\TestApiInterface class so now we have to create this class and its implementation too .


    Now create a model TestApi.php inside app/code/Webkul/TestApi/Model, this is a fake model it is not connected to any table since its is only for testing purpose, I have just defined some setters and getters for some fields.


    the above class has getTitle, getDescription and getId so we must expect that API will return these values in the response.


    Now create the interface class for the above implementation in app/code/Webkul/TestApi/Api/Data.

    Now You need to create “app/code/Webkul/TestApi/etc/di.xml” file to map interfaces with the concrete classes:

    Now create a webapi.xml file inside app/code/Webkul/TestApi/etc folder:


    the above xml files defines the routes and their permissions, the route tag attributes:

    • attribute url defines the route for the web service
    • attribute method defines the request type GET,PUT,POST or DELETE

    Now the service tag attributes:

    • class attribute is the interface class that defines the api methods.
    •  service attribute defines the exposed method

    now the resource tag defines the access control these can be three level of access:

    •  Admin : for admin level access you need to define admin resource in the resource tag.
    • Customer: for customer level access you need to set self in the resource.
    •  Guest: for guest level resources you need to define anonymous in the resource tag.
    • I have defined self so this resource will work for customer level access.

    This is the php file that you can create in your project to access the api resource

    in the above file I have used token based authentication. Magento2 provides 3 ways to access api resources :

    •  Token based authentication
    • 2: OAUTH based authentication
    • 3: Session Based Authentication

    You can learn more about it on magento2 api docs they have defined it very well:

    This is the response, taken snap from postman, you can see the below response is returned all the getters from the TestApi model in json format thats the beauty of magento2 api .

    That’s all, thanks for reading the article, if you have any queries regarding the blog please comment below.
    Thanks đŸ™‚

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


  • srmes
    This is a great article – I need to do this soon, so it will be a good reference.

    I eventually worked it out but I found it confusing why you returned the whole object in the TestApiManager class initially -it is because it needs to return an instance of the model interface, which is defined the future in the article, maybe you can tweak the ordering? or just note that this object is returned that meets an api model interface/contract that is defined later

    Wishing you good fortune illuminating strange roads of Magento 2

  • Priyanka yendhe
    I tried same module with POST method API , but its not working.. please suggest some solution for POST API.
  • Abhishek Sharma
    Where is testApiFactory located and why is it used in TestApiManagement.php file ?
  • Nasir Mahmood
    seems interesting tutorial, Can i have the files zip please. I am totally beginner to API, so having trouble with files structure. Can you please mail or share with me.
  • Jim
    Why are you making composer.json? When do you use it?
    • ashutosh srivastava (Moderator)
      composer.json is used when you want to download the module using composer, although it is not needed when you are directly installing the module.
  • Rasik Miyani
    Your explanation is pretty simple but i don’t know how magento determine which class has implementation of api interface ? means you might be missing di.xml file.
    • ashutosh srivastava (Moderator)
      Yes, di.xml file was missing, I have updated the blog and added the di.xml file, thanks
  • Ashish Viradiya
    The regitration.php filename is wrong it should be registration.php
  • shweta
    how can I see the output
    • ashutosh srivastava (Moderator)
      You can use any rest client like postman to test the api response
  • Wakar
    I’m getting following output:-

    {“message”:”Request does not match any route.”}


    I was expecting customer list as output.

    • ashutosh srivastava (Moderator)
      Hello Wakar, I dont know how you have coded it but this error clearly means, you have something wrong in webapi.xml file or you are trying hit api using wrong method(get,put,post etc) different from what you have defined in webapi.xml.
  • sid
    Hello ,

    where should i place this files composer.json, regitration.php and module.xml in magento 2, Please tell me file paths for these files.
    For above folder structure you create all files under app/code directory , But in M2 code folder is not present so i need to create code folder under add directory?? or there is another path for your created module ??

    I am new to M2 and I stuck here please help me..
    Thank you in advance.

  • Yohanes Pradono
    that only explains GET. What about PUT and POST?
    How to “catch” the json data from the request sent?
    • Webkul Support
      Hi Yohanes Pradono,
      Thanks for your interest for sure we will update it in our future blogs.
  • Abhishek Tripathi
    I am totally new to magento may be this is a silly question but I want to know that what would be the location of last file?
    • Webkul Support
      Hello Abhishek,
      The last file is for accessing the magento2 rest api that you have created, this file is not dependent to magento or php it can be in any programming language like java, python, I have just given an example of how to access it in php.
      • Webkul Support
        you can put it anywhere on your server, it should be accessible online
        • sid
          where should i place this files composer.json, regitration.php and module.xml in magento 2, Please tell me file paths for these files. I stuck here please help me..
  • Manish Joy
    I have implemented the above, it shows getJsonResponse() not defined. Please help
    • Ashutosh Srivastava
      sorry I did not define the function above, if you are coding in magento2.2 simply return the array it will automatically sent as a json response
  • Rafael CorrĂªa Gomes â™›
    Thanks for sharing!
  • Jagdish Ram
    Hi Ashutosh

    “message”: “%fieldName is a required field.”,
    “parameters”: {
    “fieldName”: “id”

    Any luck ?

  • Roberto
    I have this response:

    [message] => Consumer is not authorized to access %resources

    Any help on this?

    • Roberto
      I answer myself… it was a server configuration issue. Thanks anyways
      • Ashutosh Srivastava
        your welcome
  • Rav
    Hi Ashutosh,

    You didn’t passed value of param “customer_id” while making rest api call. How should we pass this parameter to rest api call?

    • Ashutosh Srivastava
      Sorry for late reply, there is no need to pass customer_id as I have used ‘me’ for that in ‘rest/V1/testapi/custom/me’, it will automatically check if the token is generated by customer level access, and will pass the customer_id in your function. as defined in the webapi.xml


  • How To Create Rest Based Web Api In Magento2 -
    […] How to create rest based web api in magento2 […]
  • Back to Top
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again