2
votes

I'm trying to create a REST API using Phoenix with no Ecto or brunch.

What's the syntax for creating a post function in the router/controller with parameters, but not using Ecto?

For example in Ruby/Sinatra it would look something like this:

post "/v1/ipf" do
  @weight1 = params[:weight1]
  @weight2 = params[:weight2]
  @weight3 = params[:weight3]
  @weight4 = params[:weight4]
  @goal1_percent = params[:goal1_percent]
  @goal2_percent = params[:goal2_percent]

  # etc...
end

Update

Based on Nick's answer, here's what I ended up with:

rest_api/web/router.ex:

defmodule RestApi.Router do
  use RestApi.Web, :router

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

  scope "/", RestApi do
    pipe_through :api

    scope "/v1", V1, as: :v1 do
      get "/ipf", IPFController, :ipf
    end
  end

end

rest_api/web/controllers/v1/ipf_controller.ex:

defmodule RestApi.V1.IPFController do
  use RestApi.Web, :controller

  import IPF

  def ipf(conn, params) do
    {weight1, _} = Integer.parse(params["weight1"])
    {weight2, _} = Integer.parse(params["weight2"])
    {weight3, _} = Integer.parse(params["weight3"])
    {weight4, _} = Integer.parse(params["weight4"])
    {goal1_percent, _} = Float.parse(params["goal1_percent"])
    {goal2_percent, _} = Float.parse(params["goal2_percent"])

    results = IPF.ipf(weight1, weight2, weight3, weight4, goal1_percent, goal2_percent)

    render conn, results: results
  end

end

rest_api/web/views/v1/ipf_view.ex:

defmodule RestApi.V1.IPFView do
  use RestApi.Web, :view

  def render("ipf.json", %{results: results}) do
    results
  end

end
1

1 Answers

4
votes

Ecto and Brunch don't really have anything to do w/Phoenix handling a POST. Brunch is a web asset build tool, and Ecto is a database layer.

To add this new route, you just need to add an entry in the router for the new route:

post "/v1/spf", SPFController, :spf

And then create the controller:

defmodule MyModule.SPFController do
  def spf(conn, params) do
    # do whatever
  end
end

That's it.