1

I am trying to build out an api template inside our CMS to expose a particular channel as json. I'm going to call that channel "public." Here's the template that I have put together thus far:

[
{exp:channel:entries channel="public" dynamic="no"
    limit="{segment_3}"
    offset="{segment_4}"
    orderby="{segment_5}"
}

    { "title" : "{title}", "source" : "{public_html}" }{if count < total_results},{/if}
{/exp:channel:entries}
]

There are two channel fields defined public_html and public_css that represent the stored contents of the content item. As is, it is delivering my data as text/html and I am needing to switch it to application/json to instruct the browser.

So, I tried adding

<?php header("Content-Type: application/json"); ?>

to the top of my template (moved it around and saw no changes), but it is still delivering text/html (verified through fiddler) In the long run, I can handle text/html in my service layer, but I would really prefer this to be done right.

How do I add the Content-Type: application/json HTTP Header to the template that I provided?

1 Answer 1

2

You can use the HTTP Header plugin for this:

{exp:http_header content_type="application/json"}
4
  • Thanks for that. It's good to know there is something that exists that I may be able to use, but we're looking to minimize the number of moving parts that are at work here. Do you have any suggestions on how to add the header directly into the template with a php script? Feb 28, 2015 at 20:37
  • 1
    No, I don't think there's an easy way to do it. I get what you're saying, but you've already seen that it's not so easy to set the header yourself in PHP. This is due to EE's output class. Secondly, it's generally recommended that you NOT put PHP in your templates, and that you put anything you'd do in PHP into a plugin. Feb 28, 2015 at 20:52
  • Thanks for pointing me to that. Is there a similar plugin for reading Request headers? Mar 1, 2015 at 3:17
  • Good question. I'm not aware of one that lets you read the request headers. Mar 1, 2015 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.