3

I have a django app which has html templates and I also have a command line python api which can do GET and POST requests to the django app on the server. The api can pretty much do everything that the django app can do. How do I make it such that when I access the django app through the browser it returns html but when I access it through the api it returns json?

Where will I have to put the json and what changes do I have to make to my app?

Thank you

Neeran
  • 1,753
  • 3
  • 21
  • 26

1 Answers1

7

Use different URLs for the JSON and HTML versions.

I suggest that your JSON version be available on a url like r'normal/api(?P<json_flag>/json/?)$', and have a parameter in your view to receive the json flag. You can then serve appropriately.

Naturally, your view will have to use different logic to generate HTML and JSON. I strongly suggest that you use the json module instead of a template to generate JSON.

Marcin
  • 48,559
  • 18
  • 128
  • 201
  • Thank you for your answer. Final clarification, do I need to have 2 templates? One in json and one in html for each view? – Neeran Feb 13 '12 at 12:17
  • @Jimmy: I strongly recommend that you do not attempt to mix different formats in a single template, ever. In the case of json, you should use the standard `json` module instead of a template. – Marcin Feb 13 '12 at 12:19