Getting started with AshJsonApi

View Source

Installing AshJsonApi

mix igniter.install ash_json_api

Configure your Resources and Domain and expose actions

These examples are based off of the Getting Started with Ash guide.

Add the AshJsonApi extension to your domain and resource

To set up an existing resource of your own with AshJsonApi, run:

mix ash.patch.extend Your.Resource.Name json_api

Define Routes

Routes can be defined on the resource or the domain. If you define them on the domain (which is our default recommendation), the resource in question must still use the AshJsonApi.Resource extension, and define its own type.

Defining routes on the domain

defmodule Helpdesk.Support do
  use Ash.Domain, extensions: [AshJsonApi.Domain]

  json_api do
    routes do
      # in the domain `base_route` acts like a scope
      base_route "/tickets", Helpdesk.Support.Ticket do
        get :read
        index :read
        post :open
      end
    end
  end
end

And then add the extension and type to the resource:

defmodule Helpdesk.Support.Ticket do
  use Ash.Resource, extensions: [AshJsonApi.Resource]
  # ...
  json_api do
    type "ticket"
  end
end

Defining routes on the resource

Here we show an example of defining routes on the resource.

defmodule Helpdesk.Support.Ticket do
  use Ash.Resource, extensions: [AshJsonApi.Resource]
  # ...
  json_api do
    type "ticket"

    routes do
      # on the resource, the `base` applies to all routes
      base "/tickets"

      get :read
      index :read
      post :open
      # ...
    end
  end
end

Check out the AshJsonApi.Resource documentation on Hex for more information.

Run your API

From here on out its the standard Phoenix behavior. Start your application with mix phx.server and your API should be ready to try out. Should you be wondering what routes are available, you can print all available routes for each Resource:

Helpdesk.Support.Ticket
|> AshJsonApi.Resource.Info.routes(Helpdesk.Support)

Make sure that all requests you make to the API use the application/vnd.api+json type in both the Accept and Content-Type (where applicable) headers. The Accept header may be omitted.

Examples:

  1. Create a ticket
    curl -X POST 'localhost:4000/api/json/helpdesk/tickets' \
    --header 'Accept: application/vnd.api+json' \
    --header 'Content-Type: application/vnd.api+json' \
    --data-raw '{
      "data": {
        "type": "ticket",
        "attributes": {
          "subject": "This ticket was created through the JSON API"
        }
      }
    }'
    
  2. Get all tickets
    curl 'localhost:4000/api/json/helpdesk/tickets'
    
  3. Get a specific ticket
    # Add the uuid of a Ticket you created earlier
    curl 'localhost:4000/api/json/helpdesk/tickets/<uuid>'
    

Open API

If you want to expose your API via Swagger UI or Redoc, see the open api documentation.