Best way to allow only creating new records in Phoenix while disabling all other methods [PUT, PATCH, DELETE] for a particular entity

Kindly share your ideas :slight_smile:

In the router you can limit the actions to generate routes for. See https://hexdocs.pm/phoenix/Phoenix.Router.html#resources/4-options

resources "/comments", MyApp.CommentController, only: [:new, :create]

However, if you’re trying to enforce at the context level, simply don’t expose anything other than functions related to creation to the public API.

defmodule Commenting do
  alias Commenting.Comment
  def new_comment...
  def change_comment(%Comment{} = comment, attrs \\ %{})...
  def create_comment(attrs)...
  ...

Or are you looking for authorization solutions? A bit more information might help. :slight_smile:

4 Likes

@baldwindavid

What I have in my router.ex is the following (I believe I added them as suggested by mix phx.gen.json):

 scope "/api", MyAppWeb do
    pipe_through(:api)
    resources("/clients", ClientController, except: [:new, :edit])
end

So, in order to allow only creating new records by the API endpoint I need:

resources "/clients", MyApp.ClientController, only: [:create]

I guess I don’t need :new since I am not using the HTML UI.