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

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
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
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41989 114
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement