Question about using phoenix app with the built in views and as an api at the same time

Hey all,
So my question would be :
I have a project : https://github.com/benonymus/userteamroleapi where I use the built in solution as an admin page.
And in a previous project I used an elixir phoenix app as my api only.
Example: https://github.com/Eqls/user_restfulapi_phx/blob/master/lib/user_restfulapi_phx_web/views/user_view.ex
How could I do the 2 at the same time?
I know that I need to change the views, but in what way to keep using both?
Also there is difference in the controllers too…

Thank you

I’m not 100% sure I understand your question. You can use both a JSON response and/or an HTML response depending upon how you configure things. Which part are you asking about? For example, if you call render(conn, "index", the_data: data) in your controller, it will render "index.html" if the user accept header asks for HTML or "index.json" if the accept header asks for JSON (assuming your pipeline in your router.ex allows for it). You just define both of them the same way you did in both examples and it should work for you. If that didn’t answer your question could you explain in more detail what exactly you are trying to do?

2 Likes

Thank you for the response!
So as I undertand in the views we just add both, as it is in the second example.

But in the controller, how do we add both? and how do we decide which one to return?

for example we have this code in the controller:
     def index(conn, _params) do
    users = Web.list_users()
    IO.inspect(users)
    render(conn, "index.html", users: users)
end

how would we add this part?
render(conn, "index.json", users: users)
just with an if or case?
and if so then what is the argument for it?

Thanks

Even easier than that. Change your render(conn, "index.html", users: users) to render(conn, "index", users: users), then if you have a render("index.json", users: users) function defined in your view as well as a index.html.eex in your templates folder it should render both depending on the accept header passed in. You can test this with curl like curl -XGET -H 'Accept: application/json' http://localhost:4000/users (or whatever the URL to your app is). The only other thing that can be blocking this working is if your router does not allow JSON. You’ll have to add JSON to that part in the router; add "json" to the list here: https://github.com/Eqls/user_restfulapi_phx/blob/master/lib/user_restfulapi_phx_web/router.ex#L7

1 Like

Thanks dude :grin:

Ok, im in the process of implementing it, but it doesn seems that simple,
actually instead of this:
render(conn, "index", users: users)
it needs this:
render(conn, :index, users: users)

also the controller has these flashes so that the user is notified that stuff is added:
|> put_flash(:info, "User updated successfully.")
but when we use the json opetion it gives an erro since it is not able to display it, how can this be dealt with?