gus

gus

Nerves Core Team

Best practice for phoenix project with HTML and JSON endpoints

Hi all,

I’m starting a new project where I am planning on having both JSON and HTML endpoints. I’ve been looking into some of the best ways to prevent code duplication across two separate sets of controllers, one for each response type. I think this might be the most straightforward way of going about having both an API and regular web endpoints, but I wanted to ask and see if there is a better recommended way of doing it.

I noticed that I can let Phoenix decide which templates to render by passing an atom to the template name in the render function instead of a string, which I think is pretty cool and would be a good way to achieve this goal. An example of this would be render(conn, :index, users: users) instead of separately having render(conn, "index.html", users: users) and render(conn, "index.json", users: users).

I have tested this out, and it works well. However, the main issue I am running into is with the html-specific parts of the controller. In the case of my very very simplistic test project, I experience errors on any API calls to put_flash/2 or if there is an error with the changeset and a redirect to the new or update pages (which obviously don’t exist for the json endpoint). Is there a simple way to structure this such that I can get around these html-specific lines?

I think my options would be to pattern match on the connection and have two separate controller functions (not ideal, logic duplicated) or to have separate controller modules entirely (also not ideal, duplicated code). If the best practice is to separate controller modules, what is the best file/naming structure for this?

I noticed this question is similar to this post, but since it has been 3 years since it was posted I wanted to see if there is an update or consensus to this answer.

Thanks!

TL;DR

  • Best practice for controllers that can render both JSON and HTML?
  • How to not break JSON endpoints that have calls to put_flash/2 and other html-specific functions?
  • If splitting up controllers is the best practice, what should file naming convention be? And project organization? (file structure like project_web/controllers/api/user_controller.ex and project_web/controllers/html/user_controller.ex or something different?)
  • a link to an example project on GitHub that does this would be a great bonus :smiley:

Marked As Solved

egze

egze

I would structure it like this:

html:
project_web/controllers/user_controller.ex

api:
project_web/controllers/api/user_controller.ex

You are much more flexible this way, instead of keeping it in one controller. For example:

  • you may (and probably should) have different pipelines for html and api controllers in your router.
  • you may use some api documentation library for Swagger. Then your html controller still stays clean.
  • complexity is lower, no need to worry about preparing a response based on html or json format. you just know that api controllers send json and that’s it. Testing as a result is also simpler.

Also Liked

Yunus

Yunus

Of course after finally asking here, I found the answer.

  1. mix phx.gen.html Accounts User users name:string
  2. mix phx.gen.json Accounts User users name:string --web api (and delete the extra migration)

With the --web api argument it’ll create the files in web/api and you can do MyApp.Api.UserController.

akashv

akashv

I stumbled here a little late, but you can skip additional schema and context creation by appending --no-context and --no-schema to your phx.gen.json command. This will only generate api controllers and views in the api folder (as per namespace)

Qqwy

Qqwy

TypeCheck Core Team

This is a more general response, but I believe that the predominant pattern in situations like this is to extract most/all logic from the controller-layer to an intermediate ‘domain’ layer, which is shared by the HTML- and JSON-controllers. This approach is known as ‘domain-driven-design’.

The only thing the controllers then do is to be ‘traffic cops’ redirecting the flow to/from the functions in these domain layer, and transform e.g. error responses from the domain layer to an appropriate response in the current format: for HTML you might show a flash-message whereas in the JSON-API you might want to replace the normal response with something akin {"status": "error", "message": "This was the problem"}.

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement