Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
I set default_format to json, but my REST controller still output array data
  • I copied fuel/core/config/rest.php to fuel/app/config/rest.php and set

    'default_format' => 'json',

    However, when I access a rest URL without appending the .json suffix, for example:

    /api/login/unauthorized

    is returning:
    array (size=1)
    'error' =>
    string 'unauthorized' (length=12)
    instead of:
    {"error":"unauthorized"}
    Is there a way to setup my REST controller so it will always return JSON?
  • After a bit more googling I found out that I can set:

    $this->rest_format = 'json';

    in my base controller, but my question regarding the config/rest.php file remains. Also, what's up with the formatting on this forum? Are there any guidelines as to how to format posts properly? The above post was the result of some copypasta.
  • default means default: a value used if no other means of detecting the format is available.

    I added the way the format is determined to the docs recently: http://fuelphp.com/dev-docs/general/controllers/rest.html#/format_determination

    As you can see, the default is only used as a last resort. There is almost always an ACCEPT_HEADER in the request, so in practice it will never get to the default. You get the array because you request the URL from the browser, and not through an ajax request. The accept header will be text/html, so you're get an array dump (since an array can't be converted to html).
  • HarroHarro
    Accepted Answer
    Oh, and it's considered bad practice to fix your response type.

    It should be up to the caller to specify the return format, not the API. Which is why it is implemented this way. If you want json returned, either use the ".json" extension, or specify the correct accept format.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion