API Added in 0.4.2

Uchi exposes an API for every repository, so data can be managed from outside the browser, e.g. from scripts, LLMs, or other integrations.

The API is implemented as a JSON:API.

Authentication

By default, the API uses the same authentication as the admin UI: Uchi::Api::ApplicationController inherits from your Uchi::ApplicationController, including its before_actions. See Authentication.

With session-based authentication, the API also requires a CSRF token for POST, PATCH, PUT, and DELETE requests, just like the admin UI. Send it in the X-CSRF-Token header.

Failed authentication

Uchi doesn’t control how your authentication responds to unauthenticated requests. Rails’ authentication generator, for example, redirects to the login page, so API clients receive HTML instead of a JSON:API document.

To respond with a JSON:API error instead, handle API requests separately in your Uchi::ApplicationController. With Rails’ authentication generator, override request_authentication:

module Uchi
  class ApplicationController < Uchi::Controller
    include Authentication

    private

    def request_authentication
      return super unless is_a?(Uchi::Api::ApplicationController)

      render \
        content_type: "application/vnd.api+json",
        json: {errors: [{detail: "Not authenticated", status: "401"}]},
        status: :unauthorized
    end
  end
end

API-specific authentication

To authenticate the API differently, e.g. with tokens, define Uchi::Api::ApplicationController at app/controllers/uchi/api/application_controller.rb, inheriting from Uchi::Api::Controller:

module Uchi
  module Api
    class ApplicationController < Uchi::Api::Controller
      include ActionController::HttpAuthentication::Token::ControllerMethods

      before_action do
        authenticate_or_request_with_http_token do |token, _options|
          ActiveSupport::SecurityUtils.secure_compare(token, Rails.application.credentials.uchi_api_token)
        end
      end
    end
  end
end

Uchi::Api::Controller inherits from ActionController::API. None of the admin UI’s authentication, request forgery protection, or other callbacks apply to it.

Set the current user on uchi_context the same way as in the admin UI, see Current user.

Endpoints

Given a repository whose controller_name is companies, mounted at the default /uchi path:

Method Path Action
GET /uchi/api/companies List
GET /uchi/api/companies/:id Show
POST /uchi/api/companies Create
PATCH or PUT /uchi/api/companies/:id Update
DELETE /uchi/api/companies/:id Destroy

The routing helpers are uchi_api_records_path(resource:) and uchi_api_record_path(id:, resource:), prefixed by the as option given to Uchi.routes.mount.

Media type

Responses use the application/vnd.api+json media type. Request documents must be sent with Content-Type: application/vnd.api+json, otherwise the API responds with 415. The only supported media type parameter is profile. Any other parameter, e.g. charset=utf-8, in Content-Type is rejected with 415. Accept is rejected with 406 only when every JSON:API media type it lists has unsupported parameters.

Resource objects

The resource type is the repository’s controller_name. Ids are strings.

Records are serialized using the repository’s fields for the index view when listing, and the show view otherwise. Fields for associations become relationships, all other fields become attributes:

{
  "data": {
    "type": "companies",
    "id": "12",
    "attributes": {"name": "Acme Inc"},
    "relationships": {
      "people": {"data": [{"type": "people", "id": "3"}]}
    }
  }
}

Fields named id or type aren’t included in attributes, since JSON:API reserves those names.

Relationships contain resource linkage only. Related resources can’t be included with include.

Sparse fieldsets

fields[<type>] takes a comma-separated list of fields to include, for any request that responds with records:

GET /uchi/api/companies?fields[companies]=name,people

Only fields defined by the repository can be requested, otherwise the API responds with 400. Requested fields that the view doesn’t use, e.g. a field not shown in lists, are left out. Fieldsets for other types are ignored.

Listing

Lists are paginated with page[number] and page[size]. The default page size is 25, the maximum is 100. Larger page sizes are reduced to 100:

GET /uchi/api/companies?page[number]=2&page[size]=50

The response links to the other pages, and includes totals in meta:

{
  "data": [],
  "links": {
    "first": "https://example.com/uchi/api/companies?page%5Bsize%5D=50",
    "last": "https://example.com/uchi/api/companies?page%5Bnumber%5D=3&page%5Bsize%5D=50",
    "next": "https://example.com/uchi/api/companies?page%5Bnumber%5D=3&page%5Bsize%5D=50",
    "prev": "https://example.com/uchi/api/companies?page%5Bnumber%5D=1&page%5Bsize%5D=50",
    "self": "https://example.com/uchi/api/companies?page%5Bnumber%5D=2&page%5Bsize%5D=50"
  },
  "meta": {"page": {"number": 2, "size": 50, "total": 120, "total_pages": 3}}
}

prev and next are null on the first and last page. A page beyond the last page is empty.

Searching

filter[search] is applied the same way as search in the admin UI:

GET /uchi/api/companies?filter[search]=acme

Other filters aren’t supported, the API responds with 400 for them.

Sorting

sort takes a comma-separated list of fields. Prefix a field with - to sort descending:

GET /uchi/api/companies?sort=-founded_on,name

Only fields shown in lists that are sortable can be sorted by, otherwise the API responds with 400. Fields are sorted the same way as in the admin UI, including custom sortable lambdas.

Without sort, records are sorted by the repository’s default sort order. Records that are equal by the sort order are sorted by their primary key, so pages don’t overlap.

Creating and updating

Send a resource object with the type of the endpoint. When updating, it must also have the id of the record. Client-generated ids aren’t supported when creating.

POST /uchi/api/people
Content-Type: application/vnd.api+json

{
  "data": {
    "type": "people",
    "attributes": {"name": "Jane Doe"},
    "relationships": {
      "companies": {"data": [{"type": "companies", "id": "12"}]}
    }
  }
}

When creating, only the repository’s fields for the new view are permitted, other attributes and relationships are ignored. When updating, only the fields for the edit view can be changed. Other attributes and relationships, e.g. a has_one relationship, are rejected with 403 and nothing is changed. A to-many relationship replaces all existing members. For a has_many association, removed members are deleted or have their foreign key cleared, depending on the association’s dependent option. For has_many :through and has_and_belongs_to_many associations, the join records are deleted, not the members.

Relationships only link existing records, also for has_many fields with nested fields. The nested records’ attributes can’t be changed through the API.

Status codes

Status When
200 Listed, shown, or updated. The body contains the record(s)
201 Created. The body contains the created record, the Location header its URL
204 Destroyed
400 Malformed document, invalid pagination, sort, or fields, or unsupported filter or query parameter
403 Client-generated id when creating, or attributes or relationships that can’t be updated
404 Unknown resource, id, or path, or a relationship contains resources that don’t exist
406 The JSON:API media type is only accepted with unsupported parameters
409 The type doesn’t match the endpoint, or the id doesn’t match the URL
415 The request document isn’t sent as application/vnd.api+json, or with unsupported parameters
422 Validation failed, the record couldn’t be destroyed, a relationship contains resources of the wrong type, or the CSRF token is missing or invalid

Errors

Errors are returned as error objects. Validation errors point to the attribute or relationship they relate to:

{
  "errors": [
    {"status": "422", "detail": "Name can't be blank", "source": {"pointer": "/data/attributes/name"}}
  ]
}

Errors on a foreign key, e.g. company_id, point to its relationship, /data/relationships/company. Errors that don’t relate to an attribute or relationship in the request document, e.g. errors on the record as a whole, on omitted attributes, or on related records, have no source.