Should separate controllers be used to render HTML and JSON results for same entity types?

I have already created some models and controllers using mix phx.gen.html. I need to serve context as json. My question, should I create new controllers to serve json or is it better to modify current controllers to serve html/json depending on request type?

How to create new json controllers for existing models, what is the Pheonix / Mix way to do it?

And, inside say an index method, how to check request type and serve html/json accordingly? Thanks.

It’s one of these things that are nice in theory, but rarely work well in practice.

I would highly recommend separating your HTML-rendering controllers from API serving JSON. In my experience it usually becomes tiresome to maintain those two versions, as the HTML version will more than likely pull in more/different data than JSON version as time passes.


mix phx.gen.json with --web option.

1 Like

mix phx.gen.html Accounts User users name:string

mix phx.gen.json Accounts User users name:string --web api --no-schema --no-context