inhji
Hi there,
I have a controller with an action that renders some html. Now I want to extend that action to render some json when the content type is application/json*
I was hoping I could use pattern matching to achieve this, but this does not work (the html action always gets executed):
def index(%{req_headers: [{"content-type", "application/json"}]} = conn, _params) do
json(conn, %{some: "response"})
end
def index(conn, _params) do
render(conn, "index.html")
end
This does work:
def index(conn, _params) do
headers = Enum.into(conn.req_headers, %{})
if headers["content-type"] == "application/json" do
json(conn, %{some: "response"})
else
render(conn, "index.html")
end
end
Is there a cleaner to achieve this?
Thanks!
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Just published claude-code-elixir, a plugin marketplace for Claude Code with Elixir support. These are the plugins I’ve been using for my...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex










Showing Posts 1 to 5- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
voltone
The “Content-Type” header describes the payload of the client’s request. The response format is normally negotiated based on the client’s “Accept” header and the server’s capabilities.
See:
In a standard Phoenix application you should already have something like
plug :accepts, ["html"]in one of your router’s pipelines. You can update it to["html", "json"], make sure your client sends the correct “Accept” header and checkget_format(conn)when choosing what to render.BTW, the reason pattern matching does not work is because it will only match a list where the only element is
{"content-type", "application/json"}, which is never the case.NobbZ
indexis usally called on aGETrequest, and setting acontent-typeheader does not make much sense there.Besides of that, you match on a list that has exactly one element. This is unlikely to be true for any list of headers.
Also I’m seconding @voltone, that you probably want to check for the
"accept"header instead and leverageplugs that are already available.AlchemistCamp
Another option you have is to define a render function for both an
index.htmland anindex.jsonand then just pass the action’s atom to the render function in your controller. In other words instead of havingrender(conn, "index.html"...), you’ll haverender(conn, :index...). Here’s an example from one of my apps:card_controller.ex:
With this in place, Phoenix will look for the appropriate (view) render function or template for each content type. You could have an
index.html.eex, anindex.json.eex, anindex.xml.eexand even more options all in the same template directory.What I often do with JSON is just define a render function directly in the view instead of making a template, since it’s so short and Phoenix will automatically use Jason (or whichever encoder you’ve configured) to encode your data properly.
card_view.ex:
As @voltone pointed out, you’ll need to make sure your router plug accepts includes JSON and then Phoenix will honor the Accept header coming from the front end.
Using axios (or Vue.axios in my case), you can do that with the headers field like this:
kokolegorille
Maybe this post can help too. It allows to use suffix for routes.
inhji
Thank you everybody for your answers!
I tried two approaches:
The first one involved a plug that called
get_formatand put its output to theprivatemap. This lets me pattern match on the format like i originally imagined:The approach as outlined by @AlchemistCamp ended up being more appealing to me because all I had to do was adding the json
renderfunction to the view and changing the render function in the controller: