Skip to content

API ​

A typed REST API at /api/v1/ for apps, front ends and integrations: filters, sorting, includes, safe writes through each module's own rules.

kitloom/rest-api · admins: kitloom/rest-api-filament, kitloom/rest-api-nova

Video lessons ​

Recorded in the Filament admin; the Nova admin works the same way.

A REST API for your Laravel site, documented for you
Page size and rate limit of your Laravel REST API

The site's own API at /api/v1/, for apps, front ends and integrations. One set of rules for every kind of record: the same way to filter, sort, page and include, the same answers and the same errors, whatever module the records belong to.

It is not the WordPress REST API. /wp-json/ (kitloom/api) stays for the clients that speak WordPress; this one is named and shaped the Laravel way and is what new clients should be written against.

For the site's owner ​

  • Where it answers: https://your-site/api/v1. That address lists the resources the caller may read.
  • Who may call it: anyone reads what a visitor of the site could see. To read more, or to write, a client sends a token — an application password made under API → Tokens. A token never does more than its owner may do in the admin; one made read only never writes at all.
  • API → Reference: every resource you may read, with its addresses, fields, filters and includes — what you may do, as a token of yours would. A link there opens the same as an OpenAPI document for a program.
  • API → Tokens: the application passwords, kept in WordPress REST API → Application passwords — one set of tokens for both APIs.
  • API → Settings: how many records a list answers when the client names no page size, and how many requests a minute one caller may send (0 — no limit).
  • What is in it: the site's content — every post type and taxonomy shown over REST (the same choice WordPress REST API → Settings makes for /wp-json/), the media library, and the people who wrote it — plus whatever the installed modules add. A type of your theme's own is there without a line of code.
  • While the site is closed ("coming soon", maintenance): the API reads nothing out to whoever the holding page holds — a 503 with the page's headline. The roles that see a closed site read on, and "Keep the REST API open" in Maintenance opens it to everyone, for a separate front end.
  • What a client cannot do by accident: deleting a record for good is asked about first (see "Confirmations"), and a save over somebody else's newer change is refused when the client sends the version it read.

For the client's author ​

Reading ​

GET /api/v1/notes?filter[status]=done&filter[rating][gte]=3
                 &sort=-noted_at,title
                 &include=author
                 &fields[notes]=title,rating&fields[people]=name
                 &page[size]=20&page[number]=2
PartMeans
filter[field]=athe field is a; a,b — one of them
filter[field][op]=aeq, ne, in, gt, gte, lt, lte for numbers and dates, contains for texts, null (true/false)
sort=a,-bby a, then by b downwards
include=authorthe related records, inside each record, as their own resource shows them to you
fields[notes]=a,bonly these fields (the id always comes) — also for an included resource, by its name
page[size], page[number]the page; sizes up to 100

A list answers data, links (first, last, prev, next) and meta (current_page, per_page, total, last_page, from, to); one record answers data, and meta.version where the resource keeps versions. Dates are ISO 8601 in UTC.

A name the resource does not have — in a filter, a sort, an include or a field — is a 400 that lists the names it does have. Nothing is passed over in silence.

Writing ​

POST   /api/v1/notes            {"title": "Buy tea", "rating": 4}     → 201, Location
PATCH  /api/v1/notes/7          {"rating": 5}                         → 200 (only what changes)
DELETE /api/v1/notes/7                                                → 204 (the trash, where there is one)
POST   /api/v1/notes/7/restore                                        → 200
DELETE /api/v1/notes/7?force=1                                        → 428, then 204

Send Authorization: Bearer <token>. A field that does not exist or is only shown is a 422 under its own name, as is every rule a value breaks.

Versions. GET of one record answers an ETag (and meta.version). Send it back as If-Match with a PATCH or DELETE: when somebody saved in between, the answer is 412 and nothing is written. Without If-Match the write goes over whatever is there.

Confirmations. Where a write must be confirmed the answer is 428:

json
{"message": "Delete this record for good? This cannot be undone.", "confirm_token": "…", "expires_in": 300}

Show the question to the person, then send the very same request again with the header Confirm-Token: …. The token is good for that request by that caller only, for five minutes.

The site's content ​

ResourceWhat
posts, pages, and one per post type in REST, under its REST basetitle, slug, status, content, excerpt, author_id, parent_id, menu_order, published_at, updated_at, url, featured_image_id, the ids of its terms per taxonomy (categories, tags) and meta — each only where the type has it
categories, tags, and one per taxonomy in RESTname, slug, description, parent_id, count, url, meta; a term's id is the one a post's categories lists
mediatitle, alt, caption, description, mime_type, url, width, height, sizes (an image's smaller cuts), author_id, post_id, uploaded_at
usersname, slug, url; email and registered_at for whoever lists users in the admin. Read only. filter[me]=true is the token's owner
  • A visitor reads what is published; a token reads what its owner may see in the admin — their own drafts, everyone's with the right to edit others'.
  • content answers {"html": …, "protected": …} — the text as the page shows it — and raw for whoever may edit that record. A write sends the raw text as a plain string. A text behind a password is its editors' only: html is empty and a search does not find it.
  • filter[search]=words looks in the title and the text; filter[categories]=3,5 lists what is filed under any of them; include=author, include=parent and include=featured_image bring the related records.
  • meta holds the keys the site declares for the records (register_meta() with show_in_rest, or the application's kitloom-wp-schema.meta) and no other: without declared keys the field is not there. A write sends only the keys it changes, null removes a value, and each key says who may write it.
  • A file is uploaded with a multipart/form-data POST to /api/v1/media — file, and title, alt, caption beside it — by whoever uploads files in the admin, under the library's own rules: the types it takes, the size limit. What is said of a file can be changed later; the file itself cannot. The library has no trash, so every DELETE there is for good and asks first. Uploading needs kitloom/media; without it the library is read only.
  • DELETE is the trash. No list shows it unless asked — filter[trashed]=only or with, for whoever edits the type — and POST …/restore takes a record back. A trashed term is restored in the admin.
  • A new record is a draft unless status says otherwise, and whatever the site refuses its user — publishing as a contributor, another author's post — is a 403 here too.

Not yet here: comments, and writing users.

The modules add their own: kitloom/bookings brings booking-services, booking-staff and bookings — see its README.

The document ​

GET /api/v1/openapi.json is the API as an OpenAPI 3.1 document — for a client generator, Postman, or a page of docs. It is written from the same field declarations the answers and the validation come from, and it is the caller's own: sent with a token, it describes the fields and the writes that token's owner has; without one, what a visitor may read. The API's own address links to it (links.openapi).

Errors ​

Always JSON, whatever Accept says: {"message": "…"}, and errors by field for a 422.

StatusWhen
400the query string asks for what the resource does not have
401no token where one is needed, or a wrong one
403the token's owner may not do this, or the token only reads
404no such resource or record — also one the caller may not see
405a write to a resource that is read only
412If-Match is not the record's version any more
422the values are not valid
428confirm first
429too many requests, or too many wrong tokens
503the site is closed to this caller

For the module's author ​

A module offers its records by tagging a provider of resources. The API itself never saves a model: every write goes to the resource's writer with the token's owner as the actor, so the module's own rules hold.

php
use Kitloom\RestApi\Contracts\ApiResourceProvider;

// In the module's register(); with kitloom/rest-api only in "suggest":
if (interface_exists(ApiResourceProvider::class)) {
    $this->app->tag([ReviewResources::class], ApiResourceProvider::TAG);
}
php
final class ReviewsResource extends AbstractResource
{
    public function name(): string
    {
        return 'reviews';
    }

    public function fields(?Authenticatable $user): array
    {
        return [
            Id::make(),
            Text::make('title')->required()->rules('max:120')->filterable()->sortable(),
            Integer::make('rating')->rules('min:1', 'max:5')->filterable()->sortable(),
            Enum::make('status')->of(['pending', 'published'])->filterable(),
            DateTime::make('created_at')->readOnly()->sortable(),
            Text::make('email')->visibleTo(fn (?Authenticatable $user) => $user?->can('moderate_reviews') === true),
            Integer::make('author_id')->readOnly()->filterable(),
            BelongsTo::to('author', 'users'),
        ];
    }

    // The perimeter: all this caller may ever be shown. Lists and includes are read through it alone.
    public function query(?Authenticatable $user): Builder
    {
        return $user?->can('moderate_reviews') ? Review::query() : Review::query()->where('status', 'published');
    }

    public function allows(Ability $ability, ?Authenticatable $user, ?Model $record = null): bool
    {
        return ! $ability->writes() || $user?->can('moderate_reviews') === true;
    }

    public function writer(): ?ResourceWriter
    {
        return app(ReviewApiWriter::class);   // hands on to the module's own ReviewWriter
    }
}
WhatWhere
ContractsContracts\ApiResourceProvider (the tag), ApiResource, ResourceWriter, RestoresRecords (a writer with a trash)
FieldsFields\Id, Text, Html, Integer, Number, Boolean, DateTime, Enum, Json, Ids, File; relations BelongsTo, HasMany; Filter for a filter that is no field
A field sayscolumn(), filterable(), sortable(), required(), nullable(), readOnly(), immutable() (set once, at creation), rules(), visibleTo(), resolveUsing(), describedAs()
A resource may also sayversion($record) — the ETag; confirm($ability, $record) — a question before a write; filters(); Contracts\NarrowsLists — what its lists leave out unless asked (a trash); Contracts\PreloadsRecords — what it reads for a whole page of records at once
The record's idthe Id field's column: what /{resource}/{id} and the relations find a record by — the model's key unless the resource says otherwise
A writer throwsAuthorizationException → 403, ValidationException → 422, Exceptions\RecordChanged → 412
Settingsoptions api_per_page, api_rate_limit (ApiOptions)
Configurationconfig/kitloom-rest-api.php: the prefix, page sizes, the include limit, the rate limit, how long a confirmation lasts

A field hidden from a caller (visibleTo) is in no answer and takes no filter, no sort and no write from them. A relation is read through the related resource's query(), so an included record is one the caller could have asked for directly.

Checking the declarations ​

bash
php artisan rest-api:check

reads every tagged resource the way a request would and names what is wrong: a name that is no path, two resources of one name, no Id or several, two fields of one name, a column the table does not have, required fields without a writer. It fails when anything is — run it on deploy or in CI. Who may see and do what (query(), allows()) it cannot judge: that is for the module's tests.

What the application overrides ​

  • kitloom-rest-api.content.register set to false leaves the site's own content out: only what modules tag is there.
  • kitloom-rest-api.routes.prefix moves the API; kitloom-rest-api.routes.register set to false leaves the routes to the application. A route of the application's own under the same prefix wins.
  • The admin sections: kitloom-rest-api.filament.register and kitloom-rest-api.nova.register turn them off (php artisan vendor:publish --tag=kitloom-rest-api-config).

Tests ​

From the application that installs the package: php vendor/bin/phpunit --testsuite RestApi.

Read more ​

kitloom — sites on Laravel, built for you and run with AI.
Contact · Services · License · Refunds · Privacy · Community · YouTube · [email protected]