Go REST endpoints#

The Go generator can make a REST API for each top_level struct. The endpoints use the postgres feature, so you must also enable that feature. Enable the endpoints in model.toml:

[tool.model.go]
out = "output.go"
package = "mypkg"

[tool.model.go.features]
postgres = 1

[tool.model.go.rest]
base-path = "/api"

base-path must start with /. The generator removes a trailing /.

Endpoints#

The path segment of a struct is its name in kebab-case. For example, SaveRecord becomes save-record. A struct T with the segment t gets these endpoints:

Request

Operation

Success

POST /api/t

Creates a row from the body.

201 Created with Location, ETag, the row’s URLs, and the row.

GET /api/t

Lists the rows, one page at a time (see Listings). HEAD is also served.

200 OK with the page, and Link to the next and previous pages.

QUERY /api/t

Lists the rows that the search in the body matches (see Searches), or that a declared query selects. Only a table with a search index, or a struct that declares queries, has it.

200 OK with the page, and Link to the next and previous pages.

GET /api/t/{id}

Reads the row. HEAD is also served.

200 OK with ETag, the row’s URLs, and the row.

PUT /api/t/{id}

Replaces a row that exists. It does not create a row.

200 OK with the new ETag, the row’s URLs, and the row.

PATCH /api/t/{id}

Applies a JSON Merge Patch (RFC 7386).

200 OK with the new ETag, the row’s URLs, and the row.

DELETE /api/t/{id}

Deletes the row.

204 No Content.

GET /api/t/{id}/file/{field...}

Sends the file that a rooted path in the row names, at any depth (see Files). HEAD is also served.

200 OK, or 206 Partial Content for a range, with the file.

GET /api/t/{id}/summary

Reads the row’s listing item alone (see Row summaries). HEAD is also served.

200 OK with the item.

GET /api/t/{id}/referenced_by

Lists the rows that refer to the row (see Referring rows). Only a struct that a ref field names has it. HEAD is also served.

200 OK with the page, and Link to the next and previous pages.

GET /api/t/{id}/related

Lists the rows that the row refers to, then the rows that refer to it (see Related rows). Only a struct that holds a ref field, or that one names, has it. HEAD is also served.

200 OK with the page, and Link to the next and previous pages.

The base path itself takes QUERY /api/, which searches every table at once (see Searching every table).

{id} is the value of the struct’s primary key. These conditions apply to the struct:

  • It must have at least one primary_key field.

  • Each key must be a string, an integer, a uuid, an enum, or a path. An enum key uses the name of the enum value, and a uuid key its lower-case hex, though either case is read.

  • A key can also be a ref. Its segment is the key the ref holds, or, for a ref to a struct keyed by a ref, the key at the end of that chain. That key must be one of the kinds above other than a path. A TagNote keyed by tag: ref Tag is served at /api/tag-note/{id}, so the note on tag 7 is /api/tag-note/7.

A struct with more than one primary_key field has one path segment for each key, in the order the struct declares them. Each wildcard is named after its field. A Seat keyed by hall and seat_no is served at /api/seat/{hall}/{seat_no}, so the row with hall north and seat 12 is /api/seat/north/12. Such a struct cannot have a path key, which must fill the rest of the URL, or a key field named field, which is the wildcard of its files. A listing item of such a struct without a summary holds every key field.

A path key fills the rest of the URL, so its endpoints are /api/t/{id...} and not /api/t/{id}. The segments of the key keep their / separators. A {id...} wildcard matches at least one segment, so the row keyed by the empty relative path is served on the collection itself:

Key

URL

docs/2026

/api/t/docs/2026

/docs/2026

/api/t/%2Fdocs/2026

a/../b

/api/t/a/%2E%2E/b

`` (empty)

/api/t

The Location header of a new row uses this form (see Absolute URLs). An absolute key writes its leading / as %2F, and a . or .. segment is written as %2E or %2E%2E. The router removes the unescaped forms from a URL before it matches the URL to a route. A URL with an empty segment, such as /api/t/a//b, is redirected to its cleaned form. A URL with a trailing /, such as /api/t/a/, ends in an empty segment, which no {id...} matches, so it is answered 404.

A path key with a root is keyed by the path that it resolves to (see Rooted paths), so the URL uses that path. A file of a.epub relative to /volumes has the URL /api/t/%2Fvolumes/a.epub, and the Location header of the new row uses that URL. PUT and PATCH compare the key of the body with the URL by the resolved path. Thus a body can spell the key in a different way, such as covers/../a.epub, and the row keeps the spelling of the body.

A GET of a path that has no row lists every row under that path, instead of answering 404. The listing includes rows at any depth. It has the same items and pages as the collection listing. A rooted key lists the rows by their resolved paths, which are the keys of the rows. A path with no rows under it is still 404. A rooted key’s root is listed as the collection, /api/t, or by any spelling of its resolved path.

If a struct does not meet these conditions, generation fails. Generation also fails in these conditions:

  • Two structs have the same path segment.

  • A model route uses the same method and path as an endpoint, including the file endpoint, up to wildcard names. A route that is more specific, such as GET /api/t/{id}/file/cover, is allowed, and it wins over the file endpoint.

Register the endpoints on an mdl.Router, the router the model’s routes use too (see Routing). The handlers use the request transaction, so DBMiddleware must wrap the router:

router := mdl.NewRouter()
genmodel.RegisterRestEndpoints(router)
genmodel.RegisterAllEndpoints(router) // only if the model has routes
return http.ListenAndServe(":8080", genmodel.DBMiddleware(pool)(router))

Each handler commits or rolls back the transaction before it writes the response. If the commit fails, the client gets status 500.

Row URLs#

A response that carries a row also sends the row’s URLs: a Link header (RFC 8288) for the row itself, rel="self", and one for each endpoint that the row serves below it. These responses are a read, including HEAD and 304 Not Modified, a create, a replace, a patch, and an upload. The body is unchanged.

Link: </api/owner/13>; rel="self"
Link: </api/owner/13/summary>; rel="summary"
Link: </api/owner/13/related>; rel="related"
Link: </api/owner/13/referenced_by>; rel="referenced_by"

rel

URL

Sent when

self

The row’s own URL.

Always.

summary

.../summary.

Always.

related

.../related.

The struct holds a ref field, or one names it.

referenced_by

.../referenced_by.

A ref field names the struct.

file

.../file, which a field name and the steps to a file follow.

The struct has a rooted path or file field, directly or embedded.

Each listing item that has a url has the same URLs in a urls object, keyed by rel. The URL is the row’s canonical one: a rooted path key’s is the resolved path, whatever spelling the request used. The URLs are absolute under the public URL. Follow them rather than building them; a client that does needs no change when an endpoint is added.

Listings#

GET /api/t lists the rows of T in primary-key order. Each item has the fields of the row’s summary, its rendered title and subtitle, as Markdown and as HTML, the URL of the row, and the row’s URLs by rel:

[
    {
        "fields": {"id": 1, "owner": 10, "labels": ["red", "blue"]},
        "title": "Record 1, for **Ada**: red or blue",
        "title_html": "Record 1, for <strong>Ada</strong>: red or blue",
        "subtitle": "Owned by **Ada**",
        "subtitle_html": "Owned by <strong>Ada</strong>",
        "url": "/api/record/1",
        "urls": {
            "self": "/api/record/1",
            "summary": "/api/record/1/summary",
            "related": "/api/record/1/related",
            "referenced_by": "/api/record/1/referenced_by"
        }
    }
]

In a listing of several structs, such as a search or a related listing, each item has the URLs of its own struct.

fields is the summary’s wire form, so each field is written as the row writes it, and a ref is its key. title and subtitle are inline Markdown, for a client that renders it itself, such as a terminal. title_html and subtitle_html are the same lines rendered as HTML fragments, each one paragraph’s content with no <p> around it, so it fits in a link or a heading. A field’s text is escaped, and raw HTML and javascript: links in a template are omitted, so a fragment is safe to insert as it is. subtitle and subtitle_html are left out when the summary declares none, or when it renders empty, so an item with no subtitle and no image is a single line. A struct with no summary is listed by its primary key, with no title or title_html: {"fields": {"id": 1}, "url": "/api/t/1", "urls": {"self": "/api/t/1"}}. A rooted path key is the resolved path the row is keyed by.

An item whose summary declares an image has an image key holding the image’s absolute URL, when the row sets the field. For a url field, that is the field’s own URL, resolved against its base. For a rooted path, it is the row’s file URL, <url>/file/<field>.

The Accept header selects the format, from the formats that the row itself is served in. JSON and YAML have a list of items. TOML has no top-level array, so it has an items array of tables. A listing has no ETag.

A page holds at most 100 items. A Link header (RFC 8288) points to the next page when there is one, and to the previous page after the first:

Link: </api/record?page=MTAw>; rel="prev"
Link: </api/record?page=MzAw>; rel="next"

Follow the links, and do not build the page value yourself. It is opaque, and a value the server did not write is 400. A page past the end is an empty list. The links are absolute under the public URL, the same as the item URLs.

Searches#

QUERY /api/t searches the rows of T. QUERY is the safe HTTP method with a body (draft-ietf-httpbis-safe-method-w-body). The body is the search as text/plain, in the web search syntax of SearchT:

QUERY /api/record HTTP/1.1
Content-Type: text/plain

springfield -terrace

The response is a listing of the rows that match, best match first, with the same items, formats, and pages as the collection listing. A search that matches nothing is an empty list. To get the next page, send the same body to the Link with rel="next".

Only a table with a search index takes a search (see Full-text search), and only a struct that declares queries takes a declared query. The response to GET /api/t, and to a QUERY of it, has an Accept-Query header that lists the media types its QUERY takes: text/plain for a search, then application/json for a declared query, then text/vnd.omniblack.model.query for a query a user wrote. On a table that takes none of these, QUERY is 405. A body of a type the table does not take is 415. A body without a Content-Type is read as the first type listed.

Searching every table#

QUERY /api/ searches every table with a search index at once, as Search does. It takes the same body, and its response is a listing of the rows that match in any table, best match first, so a match in one table can come before or after a match in another. Each item is the item that its own table’s listing has, with a type key naming the row’s struct, and a url under its own table’s path:

[
    {
        "type": "Record",
        "fields": {"id": 2, "owner": 10},
        "title": "Record 2, for **Ada**",
        "title_html": "Record 2, for <strong>Ada</strong>",
        "url": "/api/record/2"
    },
    {"type": "Folder", "fields": {"location": "/orchard"}, "url": "/api/folder/%2Forchard"}
]

The listing pages as a table’s search does, and its Link headers name /api/. Only the base path itself searches every table. Any other path no table has is 404, and the base path takes no method but QUERY, so GET /api/ is 405. The endpoint exists only when some table has a search index.

User-written queries#

With the find feature, QUERY /api/t takes a query in the query language as text/vnd.omniblack.model.query, on every table:

QUERY /api/record HTTP/1.1
Content-Type: text/vnd.omniblack.model.query

priority = high AND due_on < 2026-01-01 ORDER BY due_on DESC

It needs the same perms as a search, and its rows are limited the same way. The response is a listing in the order the query gives, and to get the next page you send the same body to the Link with rel="next".

A query that cannot run is a problem whose position says where, in characters from the start of the query:

{
    "title": "Unprocessable Entity",
    "status": 422,
    "detail": "\"nope\" is not a field this query can use, at position 0",
    "position": 0
}

Text that does not parse is 400. A query that parses but cannot run is 422: a field it may not name, an operator the field’s type does not allow, a value that type cannot read, free text on a table with no search index, or a query over a limit. A statement that runs too long is 503.

Declared queries#

A QUERY of a collection with a JSON body runs one of the struct’s declared queries. The body names the query and holds its params:

QUERY /api/record HTTP/1.1
Content-Type: application/json

{"query": "in_city", "params": {"city": "Springfield"}}

params holds each of the query’s params as a row’s body holds its fields, and is decoded and validated in the same way. Every param is required, a blank string is a missing value, and a value that fails its field’s constraints is a 422 whose errors give the param’s name as the path. A query that takes no params needs no params: {"query": "noted"}.

The response is a listing of the rows that the query selects, in the query’s order, with the same items, formats, and pages as the collection listing. Every query is paged here, whether or not it sets limit. To get the next page, send the same body to the Link with rel="next". As for a search, the request needs the struct’s summarize and read perms, and the listing holds only the rows that the request may find by a search (see Searches need read).

A query that finds one row redirects to that row. The response is 303 See Other, and Location holds the row’s URL, which is absolute under the public URL when the server has one. The client follows it with a GET of the row, and gets the row with its ETag. A query that finds no row is 404:

QUERY /api/account HTTP/1.1
Content-Type: application/json

{"query": "by_login", "params": {"login": "ada"}}
HTTP/1.1 303 See Other
Location: /api/account/1

A body that is not JSON, or that names a query the struct does not declare, is 400. A param compared with a path that resolves against its row must be absolute (see Declared queries), and a relative one is 422.

Row summaries#

Every table gets GET /api/t/{id}/summary, which reads one row’s item: the object that a listing of its collection has for the row, with the same fields, title, subtitle, url, urls and image, and references’ titles read in the same way. A struct without a summary has the item of its primary key alone. It is written as JSON, or as YAML or TOML when the Accept header asks and the feature is on:

{
    "fields": {"tag_id": 1, "caption": "notes"},
    "title": "notes",
    "title_html": "notes",
    "url": "/api/tag/1",
    "urls": {"self": "/api/tag/1", "summary": "/api/tag/1/summary"}
}

It takes the perm a listing takes, summarize, and not read. As in a listing, it has url, urls and a file image only when the request may also read the row. A row that does not exist is 404, and so is a row that the request may not summarize. A path key has /api/t/{id...}/summary, and the longer pattern wins as it does for referenced_by.

Referring rows#

A struct that some ref field refers to gets GET /api/t/{id}/referenced_by, which lists the rows that refer to the row, as ReferencedBy finds them. Like the search of every table, its items can come from any table: each is the item that its own table’s listing has, with a type key naming the row’s struct and a url under its own table’s path:

[
    {
        "type": "Owner",
        "fields": {"owner_id": 10, "full_name": "Ada"},
        "title": "**Ada**",
        "title_html": "<strong>Ada</strong>",
        "url": "/api/owner/10"
    },
    {"type": "Note", "fields": {"id": 3}, "url": "/api/note/3"}
]

The rows come grouped by table, in an order that is fixed for the model, then in primary-key order. A row that refers through several fields comes once. The listing pages as a collection’s does, and its Link headers name the row’s referenced_by. A row that does not exist is 404, and a row that nothing refers to lists nothing.

A path key has /api/t/{id...}/referenced_by, served by the same router as its file endpoints, and the longer pattern wins in the same way: a GET of /api/t/a/referenced_by lists the rows referring to the row a, and does not read a row a/referenced_by.

Files#

A struct that holds a path with a root, or a file field, gets a file endpoint at /api/t/{id}/file/{field...}. A path key has /api/t/{id...}/file/{field...}. For a rooted path, {field...} is the data path from the row to one rooted path, with one segment for each step:

  • a field’s name, of the row or of a struct the row embeds;

  • a list item’s index, written in decimal with no sign or leading zeros (0, 12);

  • a map entry’s key, as one segment. A / in the key is escaped as %2F. The map’s keys must be a string, an integer, an enum, or a path, as a primary key’s must; an enum key uses the name of the enum value.

The data path ends on the rooted path: a path field, a list item, or a map value. If a map’s keys are themselves rooted paths, a data path that ends on a key sends the file the key names. For a Series that embeds a list of entries and a map of notes, and a Volume whose chapters map is keyed by rooted paths:

URL

File

/api/series/1/file/folder

The row’s folder

/api/series/1/file/entries/0/file

The first entry’s file

/api/series/1/file/entries/0/extras/2

The third of the first entry’s extras

/api/series/1/file/notes/a%2Fb/sidecar

The sidecar of the note keyed a/b

/api/volume/a.epub/file/chapters/a.epub

The file the chapters key a.epub names

A GET opens the path’s root, resolves the path the same way as its field’s With method, and sends the file. A path relative_to a root base resolves against the row, through the list items and map entries that the data path went through. A path without a root has no endpoint, because the server has no filesystem to read it from.

These have no endpoint yet: a path inside a union or behind a ref, a map whose keys are another type, a path that resolves against a root other than the row, and a struct that the data path is already inside. A recursive struct is served down to its first repeat.

The response has these headers:

  • Content-Type is the type that the file’s extension maps to in the shared MIME-info database. If the extension maps to no type, the type is sniffed from the content.

  • Content-Length, and Last-Modified if the filesystem gives a modification time.

  • Content-Disposition: inline with the name of the file.

  • X-Content-Type-Options: nosniff, so that a browser does not run a stored HTML or SVG file as a page of the API.

If the file can seek, as a file in an os.Root or an fstest.MapFS can, the endpoint is served by http.ServeContent. It answers a Range header with 206 Partial Content, or with multipart/byteranges for several ranges, and an unsatisfiable range with 416. It also answers If-Range, If-Modified-Since, and If-Unmodified-Since. A file that cannot seek, such as a file from a zip archive’s filesystem, is sent whole with 200. Its response has no Accept-Ranges header, and a Range header is ignored.

The row is read in the request transaction, which ends before the file is opened. The response is a 404 problem in these conditions: the row does not exist, the data path names no rooted path, an optional field on it is not set, its list has no such item or its map no such key, the file does not exist, or the path names a directory. A file the server may not read is 403. With the auth feature, the read perm of the row’s field that the data path starts at guards each file below it.

For a path key with file endpoints, or with a referenced_by or related endpoint, the longer pattern wins: a GET of /api/t/a/file/cover sends the cover of the row a, and does not read a row a/file/cover. Only GET, HEAD and POST are affected, and a row takes no POST, so such a row can still be written and deleted. {id...} takes as many segments as it can, so a row’s key may contain a file segment, but a data path may not have file as a segment before its last. If the struct has a referenced_by or related endpoint, a field of the row with that name has no file URL under a path key, because the endpoint wins.

Uploading a file#

A POST to a file URL uploads its body as the file, and sets the rooted path the data path ends on to the path query parameter:

POST /api/series/1/file/entries/0/extras/0?path=extra.txt

path is a value of that slot, relative or absolute, and resolves as the slot’s own value would: in the field’s root, against its relative_to base, through the list items and map entries the data path went through. The file is written where it resolves, replacing any file there, and the response is the updated row with its ETag, as for a PUT.

An upload sets a slot and never adds one. The list item or map entry must exist, and so must an optional embedded struct on the way, though an unset optional path field is set. A data path that ends on the key of a map keyed by rooted paths is 405, since changing a key is a rename. An upload to a rooted primary key cannot change which file it resolves to.

The file is written with fsedit, in the request’s transaction, so it is published only if the row’s update commits, and otherwise left as it was. That needs fsedit.Middleware, outside DBMiddleware, with a root that holds the path root’s directory, and the root’s opener must return an mdl.DirFS, such as mdl.RootFS of an os.Root (see Path roots). A root whose filesystem is not one answers 405, with Allow: GET, HEAD.

The body is streamed to a file under the fsedit root’s .txn directory, and never held in memory. Nothing is locked while it arrives, and the row is not even read, so a slow client keeps no other request waiting, even one to the same row or directory. Once the body is in, the row is locked, every check below is made, and the file is moved to where the path resolves. Hence an error about the row or the path is only reported after the whole body is sent, and a change made to the row in the meantime is the row the upload sees.

A body can be at most 32 MiB (mdl.DefaultUploadLimit). Set another limit for every upload at startup with SetUploadLimit, or give some requests their own with WithUploadLimit, for example for one table’s endpoints. A negative limit means none:

mdl.SetUploadLimit(256 << 20)

func bigVolumes(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()
        if strings.HasPrefix(r.URL.Path, "/api/volume/") {
            ctx = mdl.WithUploadLimit(ctx, 2<<30)
        }
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

The upload’s other answers:

  • 400 for a missing or invalid path.

  • 404 for a row, list item, map entry, or optional embedded struct that does not exist.

  • 409 when the file’s directory, or a base the path resolves against, does not exist, when the path names a directory, or when fsedit finds the directory locked by another transaction.

  • 413 for a body larger than the limit, whether its Content-Length says so or it turns out larger while it is read. Nothing is written.

  • 422 for a relative path whose optional base field is not set, or one that would change the primary key.

  • 412 for a failed If-Match, which is checked against the row.

A path that other paths in the row resolve against, such as a folder that entries are relative_to, can only be uploaded to where a file already is. The row’s paths are resolved when it is written, before the new file is published.

With the auth feature, an upload needs the struct’s update perm, and the update perm of each field whose value it changes.

File fields#

A file field is served at .../file/<field>, with nothing after the field’s name. Its content is in the row, so the endpoints need no root, no opener and no fsedit.

A GET or HEAD sends the content, read in the request transaction with its metadata, and served by http.ServeContent. So it answers Range and If-Range as for a rooted path’s file. Its headers are:

  • Content-Type: the type sniffed when the file was uploaded.

  • ETag: the content’s SHA-256, quoted, so If-None-Match answers 304 for content the client has, whatever else changed in the row.

  • Content-Disposition: inline, with no name, since the file has none.

  • X-Content-Type-Options: nosniff.

An unset field is 404. With the auth feature, reading the content takes the field’s read perm on top of the row’s, as for a rooted path.

A POST uploads its body as the file. It needs no path parameter, and the request’s Content-Type is ignored: the server sniffs the content with http.DetectContentType, measures it, and hashes it. The body is read into memory before the row is read or locked. It is at most the field’s max_size, and at most the upload limit, whichever is smaller; past that it is a 413. A type that the field’s content_types does not allow is a 415. The row is then locked, the field’s upload hooks run, and the content is stored with its metadata, in the request’s transaction. The response is the updated row with its ETag, as for a PUT.

POST /api/account/ada/file/avatar
Content-Type: application/octet-stream

<the image's bytes>

An upload takes the struct’s update perm and the field’s own update perm, by class. So an Account declaring

  avatar:
    type: file
    perms:
      user:
        update: authenticated
      other:
        update: accounts.admin

lets a user replace their own avatar, and an admin anyone’s. A POST is used rather than a PUT or DELETE, which a path key’s {id...} would take for a row.

The field’s value in the row is only ever set by an upload. A PUT that sends the field back as it is keeps the file, and so does a PUT that leaves it out or sends null. A PUT, PATCH or POST of the collection that sets the field to anything else is refused with 422, its error at the field’s path. A request that may not read the field gets a denied write for any value it sends, even the stored one, so the answer does not confirm a guess at it. A PATCH setting the field to null clears it, and deletes the content with it; that takes the field’s update perm. Deleting the row deletes its files.

Absolute URLs#

Listings, the Location header, and a row’s Link headers are root-relative unless the server has a public URL, and then they are absolute under it: /api/t/%2Fdocs/2026/a under https://example.com/app is https://example.com/app/api/t/%2Fdocs/2026/a. Set the default once at startup, from wherever the application keeps it:

if public := os.Getenv("PUBLIC_URL"); public != "" {
    mdl.SetPublicURL(mdl.MustParseURL(public))
}

A server reached under several names gives each request its own with WithPublicURL, which overrides the default:

func publicURL(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        next.ServeHTTP(w, r.WithContext(mdl.WithPublicURL(r.Context(), baseFor(r))))
    })
}

AbsoluteURL builds the same URLs for your own handlers.

Perms#

With the auth feature, the endpoints enforce the struct’s and its fields’ perms. RegisterRestEndpoints then takes an mdl.Authorizer, which says who is asking and which perms they hold:

type sessionAuth struct{}

func (sessionAuth) Authenticated(ctx context.Context) bool {
    return userFrom(ctx) != nil
}

func (sessionAuth) Has(ctx context.Context, perm string) bool {
    user := userFrom(ctx)
    return user != nil && user.Holds(perm)
}

catalog.RegisterRestEndpoints(router, sessionAuth{})

Your own middleware, run before the endpoints, puts the user in the request’s context; the Authorizer reads it from there. RegisterRestEndpoints panics when the Authorizer is nil.

Each endpoint checks its perm before it reads the row, so a denied GET of a row that does not exist answers the same as one that does. Code that calls the postgres feature’s functions directly, outside a request, has no Authorizer in its context, and is allowed everything.

A struct whose perms are given by class also needs to know the user’s ID, their groups, and what they hold in each. The Authorizer provides them by also implementing mdl.Owner:

func (sessionAuth) UserID(ctx context.Context) (string, bool) {
    user := userFrom(ctx)
    if user == nil {
        return "", false
    }
    return user.Name, true
}

func (sessionAuth) Groups(ctx context.Context) []string {
    if user := userFrom(ctx); user != nil {
        return user.Groups
    }
    return nil
}

func (sessionAuth) HasInGroup(ctx context.Context, group, name string) bool {
    user := userFrom(ctx)
    return user != nil && slices.Contains(user.GroupPerms[group], name)
}

The group class’s perms are asked of HasInGroup, with the row’s group, and never of Has: a user holds them through their membership of the group, not their account.

Without it, every request is in the other class alone. For such a struct, an endpoint first checks whether any class could allow the request, and checks the row itself once it has read the row. The listing queries keep only the rows that a class the request is in may summarize, so a page is still full. A row’s summary is checked against the row once it is read, as a listing’s query would have filtered it. ListSummaries<Name>, SearchSummaries<Name>, Search<Name>, the search of every table, ReferencedBy, and Related all filter by the Authorizer in their context.

Field perms hold at every depth, through embedded structs, lists, maps, and unions. See Perms on embedded structs. A PUT keeps what the request may not read and the body leaves out, or sends blank or as an empty list or map, matching list items by position and map entries by key, and a denied write’s 403 names the data path of each thing it may not change. A PUT or PATCH providing a value for what the request may neither read nor update is denied whatever the value, and that 403 names only those paths, without validating the row or comparing it with the stored one. A file below a field the request may not read is denied as a denied read of the row is.

A row’s ETag covers only the fields the request may read, so it says nothing about the others’ values, and a change to one of them leaves the tag as it was. A client can write back what it read with If-Match. A field the row says is set is the exception: the tag covers that answer, so setting or clearing the field changes the tag of a request told about it, and replacing a value does not.

Bodies#

Request and response bodies are JSON. If you enable the yaml feature, a request with a YAML Content-Type is read as YAML. If you enable the toml feature, a request with a TOML Content-Type is read as TOML. A request whose Accept header prefers YAML or TOML gets a response in that format.

PATCH accepts only application/merge-patch+json or application/json. For other content types, the response is 415 with an Accept-Patch header. The patch is merged into the stored row in memory, and the result is validated. A field the patch does not name, at any depth, keeps its stored value as it is and never goes through its JSON form. A password field is written as its hash, so reading that back would make the hash the new password. A patch that names another variant of a union replaces that value with the new variant, built from the patch alone, instead of merging the old variant’s fields into it. A patch cannot change the primary key. A patch replaces a list whole, so changing a list that holds a value the request may not read needs that value’s update. A patch naming a field the request may neither read nor update is denied, even with a null.

Entity tags and conditional requests#

The ETag is a strong entity tag: a hash of the row’s values, leaving out any field the request may not read, except for whether a field its $present reports is set. A secret field adds only a digest of its value, which never leaves guarded memory, and a password field adds its hash. A YAML or TOML response has a different tag, because the representation is different.

Header

GET / HEAD

PUT / PATCH / DELETE

If-None-Match

304 Not Modified if a tag matches the tag of the response, or for *.

412 if a tag matches the row, or for *.

If-Match

412 if no tag matches the row.

412 if no tag matches the row, or if the row does not exist.

For If-Match, a tag from the JSON, YAML, or TOML representation is accepted. Weak tags (W/"...") never match If-Match. A write request locks the row (SELECT ... FOR UPDATE) before it compares the tags, so another request cannot change the row between the comparison and the write.

Errors#

Errors are application/problem+json bodies (RFC 9457) with title, status, and detail. A validation failure also lists each failed constraint in errors, with kind, path, and message.

PUT and PATCH accept a row that fails validation if it adds no violations to the stored row. For the rule, see stored rows that fail validation. If the row adds violations, the response is 422:

  • errors lists only the new violations.

  • existing_errors lists all the violations of the stored row. It has the same form as errors.

Other validation failures do not have existing_errors.

{
    "title": "Unprocessable Entity",
    "status": 422,
    "detail": "the update adds violations the stored value does not have: note: must have no more than 5 character(s).",
    "errors": [{"kind": "length", "path": "note", "message": "must have no more than 5 character(s)."}],
    "existing_errors": [{"kind": "range", "path": "id", "message": "must be no less than 1"}]
}

Status

Cause

400

The body or the {id} segment cannot be decoded, the {id...} rest of the URL is not a valid path, a listing’s page is not one the server wrote, a search’s QUERY body is not UTF-8, or a declared query’s body is not JSON or names no query of the struct.

403

The request’s user lacks a perm the request needs.

404

The row does not exist, and for a GET of a path key, no row is under it. Also a request with no user that lacks a perm.

409

The row already exists (POST), or a foreign key fails. An upload’s directory does not exist.

412

A precondition failed.

415

A PATCH or QUERY body has a content type that the endpoint does not take.

422

The body leaves out a required field, or the row fails Validate() or a database constraint. The body key does not match the path, or a patch changes the key. A declared query’s params are missing or invalid, or a path param that must be absolute is relative.

500

Any other failure. The detail is logged and not sent, except ErrNoDB, which means that DBMiddleware is missing.