Adding Content-Type when using $response->setJsonContent()

Hi all and congratulations for the amazing job on Phalcon framework ! I'm currently working on a JSON API project and I would expect that setJsonContent call would set response Content-Type header to 'application/json' automatically.

    $response = new Response();
    $response->setJsonContent(['foo' => 'bar'])
    $response->setContentType('application/json');   // get rid of this line
    return $response;

What do you think ?



45.7k

is this question ?

It is not clearly stated, but can be deducted. I'll make an edit.



24.9k

I never used the setContentType(...), and always was in JSON. At least is what I get from AJAX calls.

edited Nov '14

Oh thank you so much @Oleg for pointing me to this link, I never thought about inheritance, I didn't even know what it was, I guess I can look for a job know !

It seems that the Response object belongs to the Http namespace, we can assume that we are always using this object in an HTTP context.

Is there any situation where we put JSON content in an HTTP response without the Content-Type header actually being "application/json"?

Phalcon team implemented a method call "setJsonContent()" which is a helper for not having to json_encode() every time (I guess), wouldn't it be "okay" to also automatically set the Content-Type header to "application/json" in this method, since we are in an HTTP context and that it would be the expected behavior?

@RompePC, you don't want a response with JSON content and a Content-Type to something like "html/text", I mean, isn't it obvious ? The client must be able to process correctly the response content. It's like you're saying : "Hey buddy, here's my great vid, have a look!", and you send the guy an mp3...

Let's take an AJAX call for example:

    $.get('api.domain_name.com', function(res) {
        // Do something
    });

Here, jQuery analyses the Content-Type header and apply treatment to the response, if you specified in the response that the Content-Type is "application/json", then jQuery parse automatically the string to get you a javascript object. If the Content-Type is "html/text", you will receive a string and you'll have to parse it manually with JSON.parse(res); to obtain a javascript object. As you see, specifying the wrong Content-Type in this context forces you to do an extra step.