Magento – Magento 2 Custom REST API Json response

magento2-apimagento2.3.0

I have developed my custom rest API endpoint. Here is the code

webapi.xml

<?xml version="1.0" ?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route method="POST" url="/V1/createcustomorder">
    <service class="Demo\CreateOrderApi\Api\CreateCustomOrderManagementInterface" method="postCreateCustomOrder"/>
    <resources>
        <resource ref="Magento_Sales::create"/>
    </resources>
</route>

di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <preference for="Demo\CreateOrderApi\Api\CreateCustomOrderManagementInterface" type="Demo\CreateOrderApi\Model\CreateCustomOrderManagement"/>
</config>

Api/CreateCustomOrderManagementInterface.php

<?php
namespace Demo\CreateOrderApi\Api;

interface CreateCustomOrderManagementInterface
{

/**
 *
 *
 * @param array $orderData[]
 * @return mixed[]
 *
 *
 */
public function postCreateCustomOrder();
}

Model/CreateCustomOrderManagement.php

 <?php
 namespace Demo\CreateOrderApi\Model;

  class CreateCustomOrderManagement implements \Demo\CreateOrderApi\Api\CreateCustomOrderManagementInterface
  {

   /**
   * @return mixed[]
   */
   public function postCreateCustomOrder()
   {
     /**
     --rest of code--
     **/

     $this->response[]['dsal'] = ['estatus' => ['0' => ['codigo' => 400, 'mensaje' => 'my message']]];

   return $this->response;
   }

  } 

In my rest client, I'm expecting output like this

 {
    "dsal": {
        "estatus": [
            {
                "codigo": 400,
                "mensaje": "No such entity with customerId = 12"
            }
        ]
    }
 }

but Magento gives me output with extra braces

[
 {
    "dsal": {
        "estatus": [
            {
                "codigo": 400,
                "mensaje": "No such entity with customerId = 12"
            }
        ]
    }
 }

]   

Can anybody tell me what wrong with return type and return array in my code?

Best Answer

I had the same problem, and finally I did this:

<?php
 namespace Demo\CreateOrderApi\Model;

  class CreateCustomOrderManagement implements \Demo\CreateOrderApi\Api\CreateCustomOrderManagementInterface
  {

   /**
   * @return mixed[]
   */
   public function postCreateCustomOrder()
   {
     /**
     --rest of code--
     **/
       header("Content-Type: application/json; charset=utf-8");
       $this->response = json_encode($responseArray);
       print_r($this->response,false);
       die();
   }
  }

It is not the best solution but it's the only way it works.

Related Topic