Tom Lima
Tom Lima

Reputation: 1056

Change response format of REST API

I'm working on my REST API responses with PHP. Here is my backend that generates the responses:

  $query = $this->db->query("SELECT some_params from some_table ");
  $result = $query->result();  

  foreach($result as $row){
     $obj[] = array(
          'title' => $row['title'],
          'price' => $row['price'],
     );
  }
  print_r(json_encode($obj));

and with that I have the following response: an array of json objects

[
  {
    "title":"Marketing",
    "price":"0"
  },
  {
    "title":"SAP B1",
    "price":"10"
  }
]

What I would like to do is return a new object, something like this:

{ 
  "apiVersion": "2.0",
  "data": {
       {
          "title":"Marketing",
          "price":"0"
       },
       {
           "title":"SAP B1",
           "price":"10"
       }
   }
}

Does anyone have any idea how I could implement this? thanks!

Upvotes: 1

Views: 1052

Answers (1)

alithedeveloper
alithedeveloper

Reputation: 720

You can easily have a class or function to do that for you. Some thing like below should help,

// provided you are using php > 7 . otherwise parmas
// can become $data, $apiversion ( without typecasting )
function api_reponse(array $data, string $apiVersion)
{
   return json_encode([
       'apiVersion' => $apiVersion,
       'data'       => $data
   ])
}

You can then use,

  $query = $this->db->query("SELECT some_params from some_table ");
  $result = $query->result();  

  foreach($result as $row){
     $obj[] = array(
          'title' => $row['title'],
          'price' => $row['price'],
     );
  }

  print_r( api_response($obj, '2.0') );

Upvotes: 1

Related Questions