Skip to content

About

JSON:API spec compliant API layer for Brando CMS blueprints

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BrandoJsonApi

JSON:API spec compliant REST API layer for Brando CMS blueprints.

Auto-generates controllers, views, and routes from your existing Brando blueprints. Add a json_api DSL block and get a fully functional JSON:API endpoint with pagination, sorting, filtering, and relationship includes.

Installation

Add brando_json_api to your dependencies:

# mix.exs
defp deps do
  [
    {:brando_json_api, github: "brandocms/brando_json_api"}
  ]
end

Setup

1. Add the extension to your blueprint

defmodule MyApp.Projects.Project do
  use Brando.Blueprint,
    application: "MyApp",
    domain: "Projects",
    schema: "Project",
    singular: "project",
    plural: "projects",
    extensions: [BrandoJsonApi.Resource]

  # ... attributes, assets, relations, forms, listings ...

  json_api do
    type "projects"

    routes do
      index :list_projects
      show :get_project
    end

    hide_fields [:creator_id, :deleted_at, :marked_as_deleted]
  end
end

2. Create a view and controller

defmodule MyAppWeb.API.ProjectView do
  @moduledoc "JSON:API view for projects."
  use BrandoJsonApi.View, schema: MyApp.Projects.Project
end

defmodule MyAppWeb.API.ProjectController do
  @moduledoc "JSON:API controller for projects."
  use BrandoJsonApi.Controller,
    schema: MyApp.Projects.Project,
    view: MyAppWeb.API.ProjectView
end

3. Add the routes

# router.ex
pipeline :json_api do
  plug :accepts, ["json"]
end

scope "/api/v1", MyAppWeb.API do
  pipe_through :json_api

  import BrandoJsonApi.Router
  json_api_resources "/projects", ProjectController
end

This generates:

  • GET /api/v1/projects — list entries
  • GET /api/v1/projects/:id — get a single entry

Usage

List entries

GET /api/v1/projects
{
  "data": [
    {
      "id": "1",
      "type": "projects",
      "attributes": {
        "title": "My Project",
        "slug": "my-project",
        "status": "published"
      }
    }
  ],
  "meta": {
    "total_entries": 12,
    "total_pages": 1,
    "current_page": 1,
    "page_size": 25
  }
}

Get a single entry

GET /api/v1/projects/1
{
  "data": {
    "id": "1",
    "type": "projects",
    "attributes": {
      "title": "My Project",
      "slug": "my-project",
      "status": "published"
    }
  }
}

Pagination

GET /api/v1/projects?page=2&page_size=10

Sorting

Comma-separated field names. Prefix with - for descending:

GET /api/v1/projects?sort=-inserted_at,title

Filtering

Filter by field values:

GET /api/v1/projects?filter[status]=published&filter[language]=en

Relationship includes

Preload related resources:

GET /api/v1/projects?include=client,categories

DSL Reference

json_api block

Option Type Required Description
type String yes JSON:API resource type (e.g. "projects")
hide_fields [:atom] no Fields to exclude from the response

routes block

Entity Argument Description
index :action Context function for listing (e.g. :list_projects)
show :action Context function for a single entry (e.g. :get_project)

Router macro

json_api_resources "/projects", ProjectController
json_api_resources "/projects", ProjectController, only: [:index]

Options:

Option Default Description
:only [:index, :show] Restrict to specific actions

Auto-preloading

Asset associations (image, video, file, gallery) that are visible in the response are automatically preloaded. Gallery assets additionally preload nested gallery_objects with images.

URL-based includes (?include=client) are merged with auto-preloads.

Media URL resolution

Image, video, file, and gallery asset fields are automatically resolved to full URLs. The resolution strategy (in order):

  1. Explicit config: config :brando_json_api, media_url_prefix: "https://cdn.example.com/media/"
  2. Brando's Brando.Utils.media_url() (auto-detected at runtime)
  3. Fallback: "/media/"

Image sizes and srcset

Image sizes are enriched with width descriptors from Brando's default_srcset config, making it easy to build responsive <img srcset="...">:

{
  "listing_image": {
    "path": "images/projects/photo.jpg",
    "url": "/media/images/projects/photo.jpg",
    "width": 1700,
    "height": 1100,
    "alt": "Project photo",
    "dominant_color": "#2a3b4c",
    "sizes": {
      "small":  { "url": "/media/images/projects/photo-small.jpg",  "width": 700 },
      "medium": { "url": "/media/images/projects/photo-medium.jpg", "width": 1100 },
      "large":  { "url": "/media/images/projects/photo-large.jpg",  "width": 1700 },
      "xlarge": { "url": "/media/images/projects/photo-xlarge.jpg", "width": 2100 }
    }
  }
}

Frontend usage:

function ResponsiveImage({ image }) {
  const srcSet = Object.entries(image.sizes)
    .filter(([, s]) => s.width)
    .map(([, s]) => `${s.url} ${s.width}w`)
    .join(', ')

  return <img src={image.url} srcSet={srcSet} sizes="100vw" alt={image.alt} />
}

Hidden fields

These fields are always hidden by default:

  • id (exposed separately in JSON:API data.id)
  • creator_id, deleted_at, marked_as_deleted, password

Add more via hide_fields in the DSL.

Overriding views

You can override any view callback:

defmodule MyAppWeb.API.ProjectView do
  use BrandoJsonApi.View, schema: MyApp.Projects.Project

  # Add a computed field
  def excerpt(project, _conn) do
    String.slice(project.body, 0..200)
  end
end

Authentication

For public content (status: published), no authentication is needed.

For elevated access, use the included bearer token plug:

# config/runtime.exs
config :brando_json_api,
  bearer_tokens: [System.get_env("API_BEARER_TOKEN")]
# router.ex
pipeline :api_auth do
  plug BrandoJsonApi.Plug.Auth
end

scope "/api/v1", MyAppWeb.API do
  pipe_through [:json_api, :api_auth]

  import BrandoJsonApi.Router
  json_api_resources "/projects", ProjectController
end

Architecture

Blueprint (json_api do ... end)
    ↓  Spark DSL Extension
Transformer (persists config at compile time)
    ↓
Controller (parses URL params → Brando.Query args → context function)
    ↓
Params (pagination, sorting, filtering, includes)
    ↓
Preloads (auto-preload visible assets)
    ↓
View (JSONAPI.View — serializes schema to JSON:API format)

The package uses a Spark DSL extension that reads blueprint metadata at compile time. Controllers and views are macro-based — define them with use and they auto-derive fields, types, and preloads from the blueprint.

No changes needed to Brando core. The extensions: mechanism in Brando.Blueprint forwards extensions to Spark.

See also

  • brando_graphql — GraphQL API layer for the same blueprints via Absinthe

License

MIT

About

JSON:API spec compliant API layer for Brando CMS blueprints

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages