Architecture

Database-First API Design: Building Robust Data Layers

How to design the schema before the endpoints: constraints, relationships, indexes that match your queries, and how database errors map to API responses.

By the APIStack team··Updated ·9 min read

Rows of labelled wooden card catalogue drawers

Database-first design means settling the data model before writing endpoints: the tables, their relationships, and the rules the data must always satisfy. The API is then built on top of a schema that already rejects invalid data. This article walks through that process with PostgreSQL examples, and covers where the approach needs care. It is for developers building an API backed by a relational database.

Why start with the schema

Application code changes often and is deployed in many places: the API, background jobs, admin scripts, one-off data fixes. The database is the one component every write passes through. A rule enforced there, such as "an order always belongs to a customer" or "a price is never negative", holds no matter which code path wrote the row. A rule enforced only in the API handler holds until the first script that bypasses it.

Starting with the schema also forces the hard questions early. Deciding whether a user can have several addresses, or whether a deleted post keeps its comments, is cheaper before any endpoint or client depends on the answer.

The order of work is short: list the entities and how they relate, write the tables with their constraints, write the queries the API will need and index for them, and only then define the endpoints.

Design the tables

Normalization is the starting point: each fact is stored once, in the table it belongs to. A user's email lives in users, not copied into every row that mentions the user, so it can be changed in one place and can never disagree with itself.

The tables below hold accounts and their optional profile data. The profile uses the user's ID as its own primary key, which makes the one-to-one relationship a property of the schema instead of a convention.

SQL
CREATE TABLE users (
    id            BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email         TEXT NOT NULL,
    username      TEXT NOT NULL UNIQUE CHECK (char_length(username) BETWEEN 3 AND 50),
    password_hash TEXT NOT NULL,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX users_email_key ON users (lower(email));

CREATE TABLE user_profiles (
    user_id       BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
    first_name    TEXT,
    last_name     TEXT,
    bio           TEXT,
    avatar_url    TEXT,
    date_of_birth DATE
);

Three choices here are worth copying. Identity columns are the SQL-standard way to generate keys, and GENERATED ALWAYS stops application code from inserting its own ID values by accident. TIMESTAMPTZ stores an unambiguous point in time, where plain TIMESTAMP stores a wall-clock reading with no time zone. And the unique index on lower(email) stops two accounts registering addresses that differ only in letter case.

Normalization has a cost: reading related data takes joins. That is usually fine. Denormalize, by storing a copy or a precomputed total, only after measuring a specific slow query, and decide at the same time how the copy is kept in sync.

Enforce rules with constraints

Constraints are how the database refuses bad data. The main ones are NOT NULL, UNIQUE, CHECK, and foreign keys, all described in the PostgreSQL chapter on constraints.

This product table uses each of them. Money is NUMERIC, never a floating-point type, because floats cannot represent most decimal fractions exactly.

SQL
CREATE TABLE categories (
    id   BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name TEXT NOT NULL UNIQUE
);

CREATE TABLE products (
    id             BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    category_id    BIGINT NOT NULL REFERENCES categories(id),
    sku            TEXT NOT NULL UNIQUE CHECK (sku ~ '^[A-Z0-9]{3,}-[A-Z0-9]{3,}$'),
    name           TEXT NOT NULL,
    description    TEXT,
    price          NUMERIC(10,2) NOT NULL CHECK (price >= 0),
    stock_quantity INTEGER NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0),
    is_active      BOOLEAN NOT NULL DEFAULT true,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);

Make columns NOT NULL unless absence has a real meaning. Every nullable column is a case each client of the API has to handle, and a three-way boolean (true, false, unknown) is rarely what anyone intended.

The check on stock_quantity does more than validate input. Two concurrent requests that each try to take the last item cannot both succeed, because the second UPDATE would drive the value below zero and is rejected. An application-level check that reads the stock and then writes it has a race between the two steps.

Model relationships

A one-to-many relationship is a foreign key on the "many" side. A blog is the usual example: a post has many comments, and a comment may reply to another comment.

SQL
CREATE TABLE posts (
    id           BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    author_id    BIGINT NOT NULL REFERENCES users(id),
    title        TEXT NOT NULL,
    content      TEXT NOT NULL,
    status       TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),
    published_at TIMESTAMPTZ,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (status <> 'published' OR published_at IS NOT NULL)
);

CREATE TABLE comments (
    id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    post_id     BIGINT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
    author_id   BIGINT NOT NULL REFERENCES users(id),
    parent_id   BIGINT REFERENCES comments(id) ON DELETE CASCADE,
    content     TEXT NOT NULL,
    is_approved BOOLEAN NOT NULL DEFAULT false,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

The ON DELETE clause is a product decision written as schema. Deleting a post removes its comments (CASCADE). Deleting a user who has written posts is refused, because author_id has no cascade and the default is to block the delete. If accounts must be removable, decide what happens to their content, such as reassigning it to a placeholder account, and encode that choice.

The table-level check on posts ties two columns together: a published post always has a publication time. Clients of the API can then rely on published_at being present whenever status is published.

Index for the queries the API runs

An index is justified by a query. Write the queries behind each endpoint first, then add the indexes they need.

PostgreSQL creates an index for every primary key and unique constraint, but not for foreign key columns. The referencing side needs one whenever you look up children by parent, and whenever the parent can be deleted, since the database must find the child rows.

SQL
CREATE INDEX comments_post_id_created_at_idx ON comments (post_id, created_at, id);
CREATE INDEX comments_author_id_idx ON comments (author_id);
CREATE INDEX comments_parent_id_idx ON comments (parent_id);
CREATE INDEX posts_author_id_idx ON posts (author_id);
CREATE INDEX posts_published_idx ON posts (published_at DESC, id DESC) WHERE status = 'published';

The first index serves "comments for a post, oldest first" in one pass, because it holds the filter column followed by the sort columns. The last is a partial index: it contains only published posts, so it stays small and serves exactly the public listing.

That listing is also where pagination is decided. OFFSET makes the database read and discard every skipped row, so deep pages get slower. Keyset pagination passes the last row of the previous page instead, and reads only the rows it returns:

SQL
SELECT id, title, published_at
FROM posts
WHERE status = 'published'
  AND (published_at, id) < ($1, $2)
ORDER BY published_at DESC, id DESC
LIMIT 20;

The API exposes this as a cursor parameter that encodes the two values. Including id in the ordering makes it stable when two posts share a timestamp.

Check each query with EXPLAIN ANALYZE against a realistic volume of data. An index that the planner never uses still slows down every write to the table, so remove the ones that are not earning their place.

Map the schema to the API

Database-first does not mean the API mirrors the tables. Treat the schema as the source of truth for the data and the API as a separate contract over it.

Select columns by name. A SELECT * behind a /users endpoint will return password_hash the day someone forgets to strip it, and will silently add any new column to the public response. Listing the columns makes the response shape an explicit decision.

Keep validation in both layers, for different reasons. The API validates input so it can return a clear message for each field before touching the database. The constraints remain the guarantee, because they also cover the cases the handler cannot see, such as two requests racing to insert the same SKU.

When a constraint does reject a write, translate it into a client error instead of a 500. PostgreSQL reports a stable error code for each kind of violation. This Express handler, using the pg driver, maps them to status codes:

JavaScript
const CONSTRAINT_ERRORS = {
    '23505': [409, 'A record with this value already exists'],
    '23503': [422, 'A referenced record does not exist'],
    '23514': [422, 'A value is outside the allowed range'],
    '23502': [422, 'A required field is missing']
}

app.post('/v1/products', async (req, res, next) => {
    const { categoryId, sku, name, price } = req.body
    try {
        const { rows } = await pool.query(
            `INSERT INTO products (category_id, sku, name, price)
             VALUES ($1, $2, $3, $4)
             RETURNING id, category_id, sku, name, price, stock_quantity, created_at`,
            [categoryId, sku, name, price]
        )
        res.status(201).json(rows[0])
    } catch (error) {
        const known = CONSTRAINT_ERRORS[error.code]
        if (!known) return next(error)
        res.status(known[0]).json({ error: known[1] })
    }
})

The query uses parameters ($1, $2) for every value. Never build SQL by concatenating request input into the string.

Change the schema safely

The schema will change, and the API must keep working while it does. Put every change in a migration file under version control, applied in order by a migration tool, so that every environment has the same schema and the history is reviewable.

For a change that would break running code, such as renaming a column, split it into steps that are each compatible with the code currently deployed:

  1. Add the new column, and have the application write to both.
  2. Copy existing values across in batches.
  3. Switch reads to the new column.
  4. Stop writing the old column, then drop it in a later migration.

The same discipline protects API clients. If the response shape is defined by an explicit column list and not by the table, a schema change does not become a breaking API change by accident.

Summary

  • Decide entities, relationships and rules first; endpoints come after the schema.
  • Put invariants in constraints (NOT NULL, UNIQUE, CHECK, foreign keys) so they hold for every writer, including concurrent ones.
  • Write the queries each endpoint needs, then index for them; foreign key columns are not indexed automatically in PostgreSQL.
  • Keep the API contract separate from the tables: name the columns you return and map constraint violations to 409 and 422.
  • Change the schema through versioned migrations, in steps that stay compatible with the running code.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading