I'm attempting to use an HMVC request within an API controller. Is there a way to specify the output format of the HMVC request? Right now, if the API call sends the header "application/xml", the HMVC response comes in XML. If the API call sends the header "application/json", the HMVC response comes in JSON.
I've tried to add the following to the before() method of my base API controller:
if (\Request::is_hmvc())
{
$this->response->format = 'application/json';
}
However, I still get XML results from the HMVC request if the accept header is set to "application/xml."
This is not an HMVC request (which is internal, from one controller to a second), but a REST API request.
It is by design that it returns whatever is requested. We feel that it should not be the service, but the client who should specify in which format it wants the response. It is the most flexible solution, and very simple to implement.
You code doesn't work, because it's not an HMVC call, therefore is_hmvc() returns false.
But as said, we suggest to go for best practice, and have your rest call specify the format. Setting the correct header, or adding ".json" to the request URI is a very simple operation.
In my base API controller, I have verified that the \Request::is_hmvc() returns true by running a simple var_dump('here');exit; from within the if () structure.
I have also var_dumped the result of the HMVC request, and the first few lines look like this:
public 'body' => string '<?xml version="1.0" encoding="utf-8"?>
<xml><found><id>12</id><address>9419 N Meridian St</address><city>Indianapolis</city><state>IN</state><zip>46260</zip><lat>39.9253370</lat><lng>-86.1563990</lng><created_at>1366758185</created_at><updated_at>1366758185</updated_at></found></xml>
' (length=285)
public 'format' => string 'application/json' (length=16)
public 'uri' => ...etc...
Notice that the "headers => Content-type" and "format" do not match, and the "body" is in XML.
As it's an HMVC call, there is no HTTP header which can be used to determine the return format. As you can see in the docs, if all the other options are not configured, it will eventually hit the default, which is 'xml'.
But perhaps it's not smart to use this for internal calls. If this is an API call that is only called internally, I would not use Controller_Rest, but a standard controller, which has less overhead. If it also has to be available publicly, I would check if it's an HMVC call in the method, and if so, return a Reponse object containing an array, and not go trough the entire REST encoding stuff (and then on the calling side converting the json back to an array).
Ahhh...I see. The locations/find API call is indeed a public API method. I'm attempting to use the HMVC request in respect of the DRY principal. I tried to use the .json URL, but I got a 405 bad request. I see what you're saying about checking for HMVC within the API method. Rather than encoding/decoding I can just send the raw data. Thanks!