Dieses Blog durchsuchen

Samstag, 21. November 2015

Magento 2 shortcut to create webapi on existing model

There is a way to call your modelmethods without to produce codeoverhead in defining interfaceclasses, datainterfaceclasses and double di definition in xml files via directlinking to your models in the webapi.xml definition of your <modulename>/webapi.xml

The object-instanciator-helper-class/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php

tries to instanciate all definitions in your modules webapi.xml.

Instead of defining the interface class in the webapi.xml and add it to the di container you can directly link to your modelclass in the webapi.xml.


 app/code/<vendorname>/<modulename>/etc/webapi.xml

 <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">  
   <!-- Get taskinformation -->  <route url="/V1/test/workflowtask/:taskid" method="GET">  
     <service class="Test\Workflowtask\Model\Task" method="getByTaskid"/>  
   </route>  
 </routes>  


url is the url under which you want to reach your api
class is the class, which you want to instanciate
method is the method you want to call
parameter object defines the parameter you want to pass





The simple model looks like that:
app/code/<vendorname>/<modulename>/Models/Task.php
The Modelmethod we want to call via rest api is Task::getByTaskId()


A sample curl call on your model via api looks like that:

 curl -X GET "http://magento2.local/index.php/rest/V1/test/workflowtask/1" -H "Authorization: Bearer wiq2mg9en76fyn1fq9h14ctmryxfdu2h"

The bearer token for the request can be generated like that:
curl -X POST "http://magento2.local/index.php/rest/V1/integration/admin/token"      -H "Content-Type:application/json"      -d '{"username":"admin", "password":"test#123"}'









Keine Kommentare:

Kommentar veröffentlichen