0

i need to return the response of custom web api as JSON.

i need it to be like this:

{
  "data": [
    {
      "id": "1",
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
      "id": "2",
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "$170,750",
      "start_date": "2011/07/25",
      "office": "Tokyo",
      "extn": "8422"
    }
  ]
}

however, my module is coming out as

[
    {
      "id": "1",
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
      "id": "2",
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "$170,750",
      "start_date": "2011/07/25",
      "office": "Tokyo",
      "extn": "8422"
    }
]

My Interface is as follows:

<?php
namespace Mag\Rest\Api;

interface OrdersManagementInterface
{
  /**
   * GET for Stock api
   * @param mixed $items
   * @return string
   */
  public function getOrders();

}

My model is as follows:

<?php
namespace Mag\Rest\Model;

use \stdClass;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 * @SuppressWarnings(PHPMD.TooManyFields)
 */

class OrdersManagement
{
    protected $connection;

    public function __construct(
    ) {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $configLoader = $objectManager->get("\Magento\Framework\ObjectManager\ConfigLoaderInterface");
        $objectManager->configure($configLoader->load('frontend')); 
        $this->connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection();
    }

    /**
     * {@inheritdoc}
     */
    public function getDelayedOrders()
    {
        $sql = "Select *  FROM custom_order";
        $results = $this->connection->fetchAll($sql);
        return $results ;
    }
}
  • Can you upload all of your the code in your getOrders method? – Toan Tam Aug 28 at 17:58
  • i updated the code, thanks in advance :) – Zorox Aug 28 at 18:03
1

Update the getDelayedOrders method to:

public function getDelayedOrders()
{
    $sql = "Select *  FROM custom_order";
    $delayedOrders = $this->connection->fetchAll($sql);
    $result = ['data' => $delayedOrders];

    return $result;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.