Document API routes using ExDoc

Viewed 105

I'm new to Elixir and I am wondering if is it possible to document API routes using ExDoc? The Router is included in the documentation but not the routes (as they are not functions).

For example, here is a sample code:

scope "/api", MyApp.Api, as: :api do
  pipe_through :api

  scope "/v1", V1, as: :v1 do
    post "/test", MyController, :test
  end
end

Can I document this is ExDoc, and if yes, how?

Sorry if I missed something obvious!

1 Answers

not the routes (as they are not functions)

That is not fully true, but let's ignore that for a moment.


Depends on what you mean by the "documenting" routes. If all you want is to list all routes then you can use Phoenix.Router.routes/1:

Phoenix.Router.routes(MyAppWeb.Router)

Technically you can even use it inside @moduledoc attribute, but with one small gist - you cannot use it within MyAppWeb.Router because that module is still not fully compiled when the @moduledoc is evaluated. Fortunately you can do all magic in another module. Then in that module you can do:

@moduledoc """
Available routes:

```
#{
  for %{verb: verb, path: path} <- Phoenix.Router.routes(MyAppWeb.Router) do
    [String.upcase(to_string(verb)), " ", path, "\n"]
  end
}
```
"""

Which will result with something like:

Available routes:

POST /test

In your case.

Related