• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Formatting REST response in JSON

#1
So, I'm trying to follow the docs here:

https://codeigniter.com/user_guide/incom...stful.html

In my extended ResourceController I'm setting $format = 'json', but I always get XML.

I've run through the code of ResourceController.php, ResponseTrait.php and Negotiate.php and I can see nowhere where this property is actually used to decide the response format!

As it stands it seems like the headers are always used to determine the response.

Can anyone confirm or explain where I may have messed up?

Here's the relevant code:

<?php namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class Salutation extends ResourceController
{
    protected $modelName = 'App\Models\SalutationModel';
    protected $format    = 'json';

    public function index()
    {
        // print '<pre>'; print_r($this->model->asArray()->findAll()); exit;
        // $this->setFormat("json");
        return $this->respond($this->model->findAll());
    }


 
Reply

#2
Here's how I see the flow:

app\Controllers\Salutation.php

PHP Code:
return $this->respond($this->model->findAll()); 

vendor\codeigniter4\framework\system\API\ResponseTrait.php

PHP Code:
public function respond($data nullint $status nullstring $message '')
{
  ...
  $output $this->format($data);
  ... 

PHP Code:
protected function format($data null)
{
  ...
  $format $this->request->negotiate('media'$config->supportedResponseFormatsfalse);
  ... 

vendor\codeigniter4\framework\system\HTTP\IncomingRequest.php

PHP Code:
public function negotiate(string $type, array $supportedbool $strictMatch false): string
{
  ...
  return $this->negotiator->media($supported$strictMatch);
  ... 

vendor\codeigniter4\framework\system\HTTP\Negotiate.php

PHP Code:
public function media(array $supportedbool $strictMatch false): string
{
  return $this->getBestMatch($supported$this->request->getHeaderLine('accept'), true$strictMatch);


I think you get the picture, the property should have been used way before now.

Perhaps ResourceController is supposed to override ResponseTrait's format() method and check for $format before using $this->request->negotiate?
Reply

#3
Okay, I see this is a known and fixed bug.

https://github.com/codeigniter4/CodeIgni...ssues/2828

Sorry, I didn't know that GitHub was used for bugs.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.