I'm trying to make an endpoint for the Magento 2 Web API that simply returns plain text. Is this possible and if so, how?
I'm currently trying this:
webapi.xml
:
<route url="/V1/export/txt" method="GET">
<service class="Vendor\Module\Api\ExportManagementInterface"
method="getListForExportInTxtFormat"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
Method implementation:
/**
* @return string
*/
public function getListForExportInTxtFormat(): string
{
$lines = [];
$items = $this->getListForExport();
foreach ($items->getItems() as $item) {
try {
$lines[] = $this->createLine(
$item['status'],
$item['sku']
);
} catch (\Exception $exception) {
// Not a valid status probably
}
}
return implode("\n", $lines);
}
Now when I use this request, the output is wrapped in a single <response>
XML node:
<?xml version="1.0"?>
<response>O; CBAA80511
O; CBAA80571
A; CBAA80570</response>
Is there a way that the REST API call can just return the plain TXT, without the wrapping <response>
-node? Like this:
O; CBAA80511
O; CBAA80571
A; CBAA80570
I'm using Magento 2.1.2
Best Answer
In your request to the API, you can specify your requested response format using the HTTP header:
Unfortunately the only 2 MIME types Magento supports currently are
application/xml
andapplication/json
.The following 2 classes provide the renderer for these formats:
Magento\Framework\Webapi\Rest\Response\Renderer\Json
Magento\Framework\Webapi\Rest\Response\Renderer\Xml
You can see that both of these classes implement the interface:
Magento\Framework\Webapi\Rest\Response\RendererInterface
.You could look into creating your own plain text renderer class and using that to output your response.