GET Requests in AshJsonApi with has_many resources - how to add link prefix and nested JSON in attributes field?

There are two resources in an 1: N relationship: diary and photo.
I want to load photos from an API into the diary.
In the router, there is a prefix called “/v1/api/json,” but it doesn’t seem to appear in the related link.

diary - resource

json_api do
    type "dental_diary"

    routes do
      base("/diaries")
      post(:create)
      get(:read)
      index(:list)
      patch(:update)
      delete(:destroy)

      related :photos, :read do
        primary? true
        route("/:id/photos")
      end
    end
  end

...

relationships do
    has_many :photos, Dentallog.DentalDiary.DiaryPhoto
  end

photo - resource

...
relationships do
    belongs_to :diary, Dentallog.DentalDiary.Diary do
      attribute_writable? true
    end
  end
  1. The first question is how to add the “/v1/api/json” prefix in the related link.
  2. The second question is whether there is a way to load photos as nested JSON in attributes field.

response

{
    "data": {
        "attributes": {
            "title": "1",
            "date_of_record": "2024-02-07",
            "date_of_visited": "2024-02-07",
            "pain_of_scale": 5,
            "memo": null,
            "doctor_opinion": null
        },
        "id": "fed42b30-92ee-4557-bf66-7cd38c83443b",
        "links": {},
        "meta": {},
        "type": "dental_diary",
        "relationships": {
            "photos": {
                "links": {
                    "related": "http://localhost:4000/diaries/fed42b30-92ee-4557-bf66-7cd38c83443b/photos"
                },
                "meta": {}
            },
            "paper_trail_versions": {
                "links": {},
                "meta": {}
            }
        }
    },
    "links": {
        "self": "http://localhost:4000"
    },
    "jsonapi": {
        "version": "1.0"
    }
}

First question:

I think the prefix has to match up with how you added the AshJsonApi.Router to your Phoenix Router

scope "/v1/api/json" do
  pipe_through(:api)

  forward "/", YourRouter
end

Second Question:

You can add the include query parameter, you can find more information about it here
https://jsonapi.org/format/#fetching-includes

2 Likes

Thanks to you, the problem has been solved. I really appreciate it~!