lyo5ha

lyo5ha

GET request with JSON body - is it possible to handle?

Hi! I want to receive GET request with JSON body.

#router
...
  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", PsRbkWeb do
    pipe_through :api
    get "/order", PaymentController, :index
  end
...

# controller
...
  def index(conn, _some_params) do
    IO.inspect(conn) # empty body_params: %{} in conn
  end
...

After I made GET request to “/order” with some json in body (with header Content-Type=application/json). - have empty body_params: %{} in conn in my controller.

Here is resulting conn, sorry for length:

%Plug.Conn{
  adapter: {Plug.Cowboy.Conn, :...},
  assigns: %{},
  before_send: [#Function<1.112466771/1 in Plug.Logger.call/2>,
   #Function<0.66982185/1 in Phoenix.LiveReloader.before_send_inject_reloader/2>],
  body_params: %{},
  cookies: %Plug.Conn.Unfetched{aspect: :cookies},
  halted: false,
  host: "localhost",
  method: "GET",
  owner: #PID<0.596.0>,
  params: %{},
  path_info: ["order"],
  path_params: %{},
  port: 4000,
  private: %{
    PsRbkWeb.Router => {[], %{}},
    :phoenix_action => :index,
    :phoenix_controller => PsRbkWeb.PaymentController,
    :phoenix_endpoint => PsRbkWeb.Endpoint,
    :phoenix_format => "json",
    :phoenix_layout => {PsRbkWeb.LayoutView, :app},
    :phoenix_pipelines => [:api],
    :phoenix_router => PsRbkWeb.Router,
    :phoenix_view => PsRbkWeb.PaymentView,
    :plug_session_fetch => #Function<1.58261320/1 in Plug.Session.fetch_session/1>
  },
  query_params: %{},
  query_string: "",
  remote_ip: {127, 0, 0, 1},
  req_cookies: %Plug.Conn.Unfetched{aspect: :cookies},
  req_headers: [
    {"accept", "*/*"},
    {"accept-charset", "UTF-8"},
    {"accept-encoding", "gzip, deflate"},
    {"cache-control", "no-cache"},
    {"connection", "keep-alive"},
    {"content-length", "353"},
    {"content-type", "application/json"},
    {"host", "localhost:4000"},
    {"postman-token", "70bc9e11-1ef4-493d-a556-cf4876d28bc2"},
    {"user-agent", "PostmanRuntime/7.4.0"}
  ],
  request_path: "/order",
  resp_body: nil,
  resp_cookies: %{},
  resp_headers: [
    {"cache-control", "max-age=0, private, must-revalidate"},
    {"x-request-id", "2lonnum7h1c48rmudk000gu1"}
  ],
  scheme: :http,
  script_name: [],
  secret_key_base: :...,
  state: :unset,
  status: nil
}

So, the question is: Is it possible to receive any json data in GET request body and access it form controller? (Or I have to give up and use POST with JSON body). Please, guide me to the right direction.

Marked As Solved

lyo5ha

lyo5ha

Not supposed to, but I like to have such option. :grinning:

I found quite hacky solution:

# controller
...
  def index(conn, _some_params) do
    {:ok, body, _conn} = Plug.Conn.read_body(conn)
    IO.inspect(body)           # got string with escape characters, but better than nothing 
  end

I think to write custom plug and put this body to some custom field in conn. By the way, Plug.Parsers don’t parse GET requests, so no point to add custom handler for GET requests into parsers. I hope, this will help somebody.

Also Liked

NobbZ

NobbZ

HTTP GET does not have a body as far as I remember…

NobbZ

NobbZ

Ohyeah, you are right, according to RFC 7231:

A payload within a GET request message has no defined semantics;
sending a payload body on a GET request might cause some existing
implementations to reject the request.

So, according to the RFC, you either should be able to access the body or never see the request.

Perhaps the pipeline doesn’t parse the body as it does not expect it? How is your plug parser configured?

Where Next?

Popular in Questions Top

mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
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
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
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
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
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
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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement