How to do bulk inserts in ash json api

I want to insert multiple records in a single post request.

Example:

This is my POST API URL: /article/article_id/add-comments, and I want to add multiple comments at the same time.

I tried sending the payload as a list, like this:

For example,

      [
          {
            type: "articles",
            attributes: {
              "comments" => "some comments"
            }
          }
      ],
      [
        ...
      ],

However, I am getting an invalid_body error.

Please provide an example of how to do bulk inserts in Ash JSON API.

We don’t currently have tools to automatically build bulk action endpoints (although I’d very much like to do this).

So for this you’d need to define a generic action

defmodule YourCustomMapTypeOfFields do
  use Ash.Type.NewType, subtype_of: :map, constraints: [
    fields: [
     field1: [type: :integer, ...]
     ....
    ]
  ]
end
action :bulk_create, {:array, __MODULE__} do
  argument :inputs, {:array, YourCustomMapTypeOfFields}, allow_nil?: false

  run fn input, _ ->
    # use Ash.bulk_create with `input.arguments.inputs` 
  end
end

Then you can use route/3 to make a generic action route:

route :post, "/path/to/your/route", :bulk_create
1 Like

When I try to apply your solution, I get a runtime error saying that MODULE is not a valid type. The error message mentions that valid types include any custom types or the following short codes (alongside the types they map to). Do I need to specify my return type as the custom Ash type module?

Ah, sorry about that

action :bulk_create, {:array, :struct} do
  constraints [items: [instance_of: __MODULE__]]
  argument :inputs, {:array, YourCustomMapTypeOfFields}, allow_nil?: false

  run fn input, _ ->
    # use Ash.bulk_create with `input.arguments.inputs` 
  end
end
1 Like