Skip to content
← All articles

Technical guide · 1,706 words

How to Generate CRUD APIs Safely

Learn how to design generated CRUD APIs around shared schemas, scoped access, validation, stable endpoints, and predictable error handling.

How to Generate CRUD APIs Safely

Generating CRUD endpoints is straightforward. Generating endpoints that continue to respect a changing schema, access policy, and record boundary is the harder part. In Dashier, the REST API is built around a data source: a project-scoped source has a slug, ordered field definitions, and endpoint policies, and those definitions are reused by the dashboard and the API.

That shared contract matters. If a form validates one shape while the API accepts another, the two entry points eventually disagree about what a valid record is. The implementation therefore loads the source and its fields before handling a request, then passes the same field definitions to the read and write paths.

Make the data source the API contract

A source slug is the public identifier in /api/v1/{slug}. The slug is URL-safe, limited to 63 characters, and unique within its project. Treat it as a durable API key rather than a display label: changing it changes the route clients call.

The field definition contains the machine key, type, required and nullable settings, default value, uniqueness flag, options, and position. The supported types include text, numbers, booleans, email, phone, URLs, dates, JSON, files, images, enums, references, arrays, and rich text. The field module is the single source of truth for record validation, forms, and API contracts; adding another copy of those rules in a route would make drift likely.

A request first resolves its organization, project, and source. A caller can authenticate with an API key in x-api-key or Authorization: Bearer; without a key, the request must provide org and project query parameters, with an optional session for member-based access. The server looks up the source by slug under the resolved project. A client-supplied organization ID is not used as proof of tenancy.

Validate at the write boundary

The generated routes accept JSON objects for create and update. Validation is performed by the shared record writer, not just by a UI form. Values are coerced where the field type supports it—for example, numeric strings can become numbers, boolean spellings are normalized, JSON strings are parsed, and dates have normalization for supported input formats—then the resulting values are checked with a Zod schema built from the persisted field definitions.

Defaults are applied when a field is absent. Nullable and required are separate properties in the implementation, so a value may be omitted, explicitly set to null, or rejected according to the field definition. An update merges the request over the existing record before validating the complete result. This makes PUT behave as a validated merged update rather than allowing a partial request to leave the record in an invalid state.

The API does not accept an id field as ordinary input. ID-type fields are assigned by the server, and an update restores the existing value instead of letting the request replace it. Reference fields are checked against the target data source, and fields marked unique are checked for conflicts within the source before the write. Validation failures return 422 with an issues array; malformed JSON or a non-object body returns 400.

The current schema builder strips unknown keys rather than rejecting them. That is an important implementation detail when documenting the contract: callers should send defined field keys, but the current route does not provide the strict-unknown-field behavior sometimes recommended for a new API. The production rule is the code and its tests, not an example that promises a stronger guarantee than the implementation provides.

Keep list work bounded and predictable

GET /api/v1/{slug} supports text search, exact field filters, sorting, and offset pagination. The route accepts search, sort, dir, page, and perpage; perpage defaults to 20 and is capped at 100. Filters use the filter_{field-key}=value convention. Search is applied to searchable text-like fields, while sorting can use a field key or the record timestamps.

The current list implementation reads at most 1,000 rows for a source, sorts and paginates that result in application code, and returns data, total, page, and per_page. That is a useful MVP boundary, but it is not cursor pagination and it is not an unbounded query engine. If a source outgrows that scan limit, the implementation needs an indexed query and a deliberate pagination design before the API can promise larger-scale behavior.

Unknown sort fields produce a 400 response. Filters are only applied when their keys exist in the loaded field definitions. The list response includes record metadata (id, createdby, createdat, and updated_at) alongside the stored values; consumers should treat those fields as response data, not as writable input.

A single-record request uses GET /api/v1/{slug}/{id} and returns 404 when the record is not found under that source. PUT updates the record after merging and validating the input. DELETE removes it and writes a record.delete audit entry. Creates and updates also write audit entries, and creates can dispatch the record-created notification path used by the application.

Resolve authentication and policy separately

Authentication identifies the caller; the endpoint policy determines whether that caller may use the method. Each source method has an enabled flag, an API-exposure flag, an access mode, an allowed-role list, and a per-minute rate limit. The modes are public, authenticated, and role-protected.

For an authenticated policy, API keys need the operation scope: read for GET and write for the other generated methods. Role-protected key access requires the admin scope; a session can pass as the owner or through an explicitly allowed role ID. Revoked keys are rejected, and keys are resolved by a hash rather than by comparing or logging raw key material.

The implementation also applies a member source allowlist to session callers. Source access is therefore not implied merely by having an organization session. Keep the method decision explicit as well: the route resolves GET, POST, PUT, or DELETE before checking the policy, rather than treating every request as the same operation in documentation or client code.

Rate limiting is applied per source, method, and API-key identity, or per forwarded IP address when no key is present. The configured policy value defaults to 120 requests per minute when unset, and an exceeded request returns 429 with X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After. The limiter is currently an in-memory sliding window, so it is best-effort per server instance rather than distributed enforcement.

Test the generated contract at its boundaries

Happy-path create, list, update, and delete calls do not exercise the parts most likely to regress. Tests for a generated source should cover invalid types, defaults, nullability, unknown input keys, duplicate unique values, invalid references, server-owned IDs, missing records, malformed request bodies, and the list limits and sort rules the route actually exposes.

Authorization tests should vary the endpoint mode, credential type, key scope, session role, source allowlist, revoked state, disabled state, and API-exposure flag. A key with read should not be treated as a write credential, and a session that lacks source access should not receive records merely because it belongs to the organization. Assert both the status and the response shape so a later route change cannot quietly turn a client-handled validation error into an opaque server failure.

Choose the integration path deliberately

Start with the source, not the URL: identify the project and source slug, inspect field definitions and method policies, then choose an API key or session-backed request. Only then map form fields to the JSON body and table controls to search, filter, sort, dir, page, and perpage.

Check that the endpoint is exposed, enabled, and writable before building against a happy-path POST. A read-only integration can use a key with read; writes require write access. A role-protected policy is different: a key needs admin, while a session must be the owner or have configured role ID. Treat 401, 403, 404, 422, and 429 as distinct outcomes.

Plan schema changes without inventing versions

The routes have no schema-version negotiation or compatibility header, so persisted field definitions are a contract. Keep machine keys stable; changing a display name is easier to absorb than renaming a key used in values, filters, sorts, or request bodies.

When adding a field, check required, nullable, and default settings together: a default can make omission valid, while non-nullable can reject explicit null. For a type change, test existing values and coercion. Enum inputs must match persisted options; references must be existing target record UUIDs; arrays should preferably be JSON string arrays.

There is no migration or alias behavior for a renamed source or field, so coordinate updates explicitly. Unknown body keys are stripped by the current Zod schema, not strictly rejected.

Keep request and response boundaries explicit

Create and update bodies are flat JSON field objects, not the list response shape. A returned record wraps the row in data and includes id, values, createdby, createdat, and updated_at; only values belongs in a subsequent write body. POST returns 201, delete returns { ok: true }, missing records are 404, malformed input is 400, and validation is 422 with issues.

The list total is the number of rows in the bounded result, not a database-wide count. The implementation fetches up to 1,000 rows, applies filters, sorts in application code, then slices the page. Keep per_page between 1 and 100; this endpoint is not cursor pagination or an unlimited reporting interface.

Put credentials where they cannot become data

Keep API keys in a server-side secret store and send them in the x-api-key or Bearer header. Never put a raw key in a browser bundle, query string, record, log, or source-controlled example.

Test the sequence, not only each handler

Tests should cover searchable, unique, reference, server-generated ID, and nullable/defaulted fields. Exercise create, filtered list, merged update, fetch, and delete. Add unknown sort, per_page=0 and 101, malformed JSON, nonexistent references, revoked or insufficient-scope keys, disabled methods, and rate limiting. Assert status and JSON shape so edits cannot quietly change the contract.

Safe CRUD generation is not about producing four handlers and calling the job finished. It is about keeping the persisted field definition, source lookup, validation path, policy check, bounded list behavior, and audit trail aligned. Dashier’s current API provides that foundation for project-scoped REST records; it does not turn the CRUD layer into a general workflow engine or promise capabilities outside the checked-in routes.

Dashier is admin infrastructure for modern applications. Learn how the product works in the documentation or explore features.