External APIs with Ash resources

I’m currently experimenting with Ash for a liveview app that interfaces with an external json api (Microsoft graph api). I would like to call an endpoint of that api and use what it returns as parameters for a resources actions.

What I’m struggling with is where to put the request. Initially I added a free standing function that I call which then calls a create action. What I’m wondering is, is there a happy path to make a request inside an action and then use those parameters?

My attempt was to use a before transaction hook to make the request and then force the changes on the change set before proceeding with the action but that felt clunky. Is there an easier way to do this?

So you’ve already found the first way, which is to use a before transaction hook. Another option is to use a “generic action”. Generic actions allow for things like this:

# returns a struct
action :something, :struct do
  # that is an instance of this resource
  constraints [instance_of: __MODULE__]
  argument ...
  argument ...
  argument ...

  run fn input, _ -> 
     with {:ok, external_result} <- call_api do

@brady131313 post some code examples if you get a chance I’d love to see it! I also wonder about best practices to fit an api into an ash resource.

A high level idea; it would be really cool if Ash resources could be shared like a package somehow. Lots of common apis out there we all use. That way if you write a nice Ash resource for MS graph, I could easily import the implementation somehow. I guess thats standard package publishing but with Ash’s lego block setup I wonder if tooling could make it easier to share via a config flag.