# OpenAPI Schemas From the Database: Which Parts to Generate and Which to Write by Hand

> Generate the read model from the database: column types, `varchar` lengths, enum values, nullability and descriptions are facts the table already enforces. Write the request bodies yourself, because a `NOT NULL` column with a default or an identity is required in a row but must not be required on create, and decide by hand how `bigint`, `numeric` and timestamps without a time zone travel as JSON.

Source: https://schemity.com/blog/generate-openapi-schema-from-database/

Generate the response side of your OpenAPI schemas from the database, and write the request side by hand. A table already knows each column's type, its `varchar` length, whether it can be `NULL`, which values an enum allows and what the column is for, and copying those facts by hand is how an API comes to promise a 255-character name to a column that holds 120. But a stored row and a create request are different shapes, and five things the table says are either wrong for a request body or not decided by the table at all.

Everything below was run on PostgreSQL 18.6 in a throwaway container, with the exported schema checked by the Python `jsonschema` validator (4.26, format checking on). The table is a small billing schema:

```sql
CREATE TABLE customers (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL
);

CREATE TYPE invoice_status AS ENUM ('draft', 'sent', 'paid');

CREATE TABLE invoices (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id bigint NOT NULL REFERENCES customers (id),
    number varchar(20) NOT NULL UNIQUE,
    status invoice_status NOT NULL DEFAULT 'draft',
    total numeric(12,2) NOT NULL,
    issued_at timestamp NOT NULL DEFAULT now(),
    paid_at timestamptz
);
```

## What does a database column tell an OpenAPI schema?

A column gives OpenAPI its type, format, length limit, nullability, allowed values and description, and each one maps to a JSON Schema keyword.

| Column | OpenAPI 3.1 property | Where it comes from |
|---|---|---|
| `number varchar(20) NOT NULL UNIQUE` | `type: string`, `maxLength: 20`, in `required` | the type's length and `NOT NULL` |
| `status invoice_status` | `type: string`, `enum: [draft, sent, paid]` | the enum type's values, in declared order |
| `customer_id bigint REFERENCES customers` | `type: integer`, `format: int64` | the type; OpenAPI has no keyword for a foreign key |
| `paid_at timestamptz` (nullable) | `type: [string, "null"]`, `format: date-time` | the type, and the missing `NOT NULL` |
| `COMMENT ON COLUMN ...` | `description` | the column comment |

Two of these line up more exactly than you might expect. PostgreSQL counts `varchar(20)` in characters, and JSON Schema's `maxLength` counts characters too: 20 emoji fit in `number`, the 21st fails with `value too long for type character varying(20)`, and the validator accepts and rejects the same strings. And OpenAPI 3.1 dropped the `nullable` keyword in favour of a type list, `type: ["string", "null"]`, which says exactly what a nullable column says.

The ones that have no keyword are the relational facts and the arbitrary ones. A foreign key and a `UNIQUE` constraint constrain a set of rows, not one JSON object, so an exporter has to carry them as vendor extensions. A `CHECK` is per row, but it is any SQL expression, with no general translation to JSON Schema.

## Where do the database and the API disagree?

They disagree wherever a stored row and a JSON message are different things: on what a client must send, and on how a value is written as JSON.

| Column | What the table says | What the API needs | What breaks if you copy the table |
|---|---|---|---|
| `id ... GENERATED ALWAYS AS IDENTITY` | `NOT NULL`, so required | absent from the create body | PostgreSQL refuses a client's id: `cannot insert a non-DEFAULT value into column "id"` |
| `status ... DEFAULT 'draft'`, `issued_at ... DEFAULT now()` | `NOT NULL`, so required | optional on create | a create body that relies on the default fails validation |
| `id bigint` | `integer`, `int64` | often a string | JavaScript reads `9007199254740993` as `9007199254740992` |
| `total numeric(12,2)` | exact decimal | a number or a string, by choice | `row_to_json` writes `1250.00` as a JSON number, which most clients parse as a float |
| `issued_at timestamp` | a date and time with no zone | a format the value passes | `2026-11-23T09:51:04.766931` fails `format: date-time` |

The first two are the request problem. `NOT NULL` describes the row after the database has filled in the identity and the defaults, so `required: [id, status, issued_at, ...]` is right for a response and wrong for `POST /invoices`. JSON Schema has half an answer: `readOnly: true` marks a value "managed exclusively by the owning authority", which fits an identity id. The table does say it for a defaulted column, with `NOT NULL` plus `DEFAULT`, but OpenAPI has no keyword for optional on create and always present on read, so that split is yours to write.

The `bigint` row is about the client, not the database. PostgreSQL's `to_json(9007199254740993::bigint)` writes the exact number, and `JSON.parse` in Node rounds it to `9007199254740992`, because a JavaScript number is exact only up to 2^53 - 1. Many APIs send 64-bit ids as strings for that reason. The table cannot make that call, and an exporter that turned `bigint` into a string would describe what the database returns wrongly.

The timestamp row is the one that fails validation outright. JSON Schema's `date-time` format is RFC 3339's, and RFC 3339 requires a time offset, `Z` or `+hh:mm`. In a UTC session, PostgreSQL's `row_to_json` writes the `timestamptz` column as `2026-11-23T09:51:04.768962+00:00`, which passes, and the `timestamp` column as `2026-11-23T09:51:04.766931`, which fails. A `timestamp` column records a clock reading, not an instant. The OpenAPI Format Registry has a format for exactly that, `date-time-local`, "RFC3339 date-time without the timezone component", and a validator that does not know it ignores it, which beats one that rejects every value. The lasting fix is in the database column: the [timestamp vs timestamptz](https://schemity.com/blog/postgres-timestamp-vs-timestamptz/) post covers when a column should carry the zone.

## Should you generate OpenAPI schema from database tables?

Yes for the response models, as a draft you check against the database whenever the schema changes, and no for the request bodies and the paths.

| Approach | Where the schema comes from | What it gets right | What it leaves to you |
|---|---|---|---|
| Database first: PostgREST | the PostgreSQL catalog, served as Swagger 2.0 on the API's root path | every column, length and comment, always current | the API is the exposed schema; request and response share each table's or view's columns |
| Code first: FastAPI and similar | the type declarations in your handlers | request and response models that differ | keeping the models in step with the columns |
| Hand-written YAML | an engineer copying the tables | anything you choose to design | every length, enum value and nullability, copied once and then drifting |
| Generated draft plus hand-written requests | an export of the tables, then edits | the read model matches the table on day one | request bodies, id and number encoding, paths |

[PostgREST](https://docs.postgrest.org/en/stable/references/api/openapi.html) is the purest database-first case: it "automatically serves a full OpenAPI description on the root path", with each `COMMENT ON` as a description, because in PostgREST the exposed tables, views and functions are the API. Shaping what clients send means writing views and functions for it. Code-first frameworks have the opposite problem. Their schema is generated from your models, so it is always consistent with the code, and the code is what drifts from the database: a model that says `max_length=255` over a `varchar(120)` column is valid OpenAPI and a runtime error.

The useful middle is to treat the database as the source of the facts and the API as the source of the shapes. Export the tables, compare the export with your models when a migration lands, and fix the models where they promise something the column cannot hold. That comparison is where the export earns its keep, more than as a first draft.

## How Schemity exports OpenAPI 3.1 from your database

Schemity writes one OpenAPI 3.1 schema per table from the diagram it reads from your database, with the database's own type kept beside every JSON type.

Schemity is database design software that reads your live database, shows the impact of every schema change before it runs, and keeps the diagram as a file in Git. [Connect it to PostgreSQL](https://schemity.com/doc/connect-postgresql/) and it reads the `invoices` table above, including the values of `invoice_status` in their declared order. Select `status` and press Cmd+O (Ctrl+O on Windows and Linux), and the Field details panel lists them beside the canvas, with the column's keys, default and description:

![Schemity with the customers and invoices tables read from a PostgreSQL 18 database and the status column selected; the Field details panel for invoices.status reads type INVOICE_STATUS, crosses for PK, FK, Unique and Nullable, default draft, ENUM values (3): draft, sent, paid, and the column comment as its description: Billing state: draft until sent to the customer, sent until paid in full, then paid](https://schemity.com/images/blog/generate-openapi-schema-from-database/canvas-invoices.webp)

**Export > OpenAPI file** then saves `<name>.openapi.json`, which opens in a preview with Copy and Save first. The `invoices` part of it:

```json
"invoices": {
  "type": "object",
  "required": ["id", "customer_id", "number", "status", "total", "issued_at"],
  "properties": {
    "id": { "type": "integer", "format": "int64", "x-db-type": "bigint" },
    "customer_id": {
      "type": "integer", "format": "int64",
      "x-references": "customers.id", "x-db-type": "bigint"
    },
    "number": {
      "type": "string", "maxLength": 20,
      "x-unique": true, "x-db-type": "varchar(20)"
    },
    "status": {
      "type": "string", "enum": ["draft", "sent", "paid"],
      "x-db-type": "invoice_status"
    },
    "total": { "type": "number", "x-db-type": "numeric(12,2)" },
    "issued_at": {
      "type": "string", "format": "date-time-local",
      "x-db-type": "timestamp"
    },
    "paid_at": {
      "type": ["string", "null"], "format": "date-time",
      "x-db-type": "timestamptz"
    }
  }
}
```

![The Export ERD as OpenAPI file preview in Schemity for pg_demo.openapi.json, 86 lines, scrolled to the invoices schema: the end of customer_id with x-references customers.id and x-db-type bigint, issued_at with type string, format date-time-local and x-db-type timestamp, and number with maxLength 20 and x-unique true, the keys in green and the values in blue, above the Copy, Save file and Close buttons](https://schemity.com/images/blog/generate-openapi-schema-from-database/openapi-export-preview.webp)

It describes the data, not an API, so it makes none of the decisions above for you. `required` is the stored row's: `status` and `issued_at` are in it, and the identity `id` is not marked `readOnly`, so the create body is still yours to write. The relational facts ride along as extensions, `x-references` for a foreign key and `x-unique` for a unique column, and `x-db-type` keeps `numeric(12,2)` and `bigint` visible where the JSON type alone would lose them. A generated column is marked `readOnly`, a nullable enum lists `null` among its values (without it, the validator rejects a `null` the type allows), and a `timestamp` without a time zone gets `date-time-local` instead of the `date-time` its values would fail. Defaults, indexes, `CHECK` constraints and views are left out, so a status kept as a `CHECK (status IN (...))` list rather than an enum type exports as a plain string.

The descriptions are the column comments the [data dictionary](https://schemity.com/doc/data-dictionary/) shows, so documenting a column once fills both. The other export formats are described in [Export SQL and other formats](https://schemity.com/doc/export-sql-ddl/); OpenAPI is one of the exports in Schemity Pro.

## Generate the facts, write the shapes

Understand your schema first, then let the API take its facts from it: types, lengths, enum values, nullability and descriptions come from the tables, while what a client sends, and how ids, decimals and timestamps are written as JSON, are API decisions to make on purpose.

The column-level choices behind two more of the five mismatches have their own posts: [UUID vs bigint primary keys](https://schemity.com/blog/postgres-uuid-vs-bigint-primary-key/) and [numeric vs double precision vs money](https://schemity.com/blog/postgres-numeric-vs-double-precision-vs-money/). [Enum vs check constraint vs lookup table](https://schemity.com/blog/postgres-enum-vs-check-constraint-vs-lookup-table/) decides whether a status reaches the export as an `enum` list at all. For the descriptions, [column comments without a migration](https://schemity.com/blog/column-comments-without-a-migration/) shows how to write them where the export can read them.

## Frequently asked questions

### How do I generate OpenAPI schema from database tables?

Read each table's columns and map them: the column type to a JSON type and format, `varchar(n)` to `maxLength`, `NOT NULL` to `required`, enum values to `enum`, and column comments to `description`. PostgREST serves such a description of a PostgreSQL database on its root path, and Schemity exports one OpenAPI 3.1 schema per table from its diagram. Treat the result as the response model and write request bodies separately.

### Should OpenAPI schemas match the database tables exactly?

The response model should agree with the table on types, lengths, nullability and allowed values, or the API promises data the database cannot hold. The request model should not match it: an identity id and columns with defaults are required in a stored row but should be optional or absent when a client creates one.

### Why does a PostgreSQL timestamp fail OpenAPI date-time validation?

Because `format: date-time` means an RFC 3339 date-time, which must end in `Z` or an offset such as `+07:00`. A `timestamp` column without a time zone reads back as `2026-11-23T09:51:04.766931`, with no offset, and a validator that checks formats rejects it. A `timestamptz` column reads back with an offset and passes. For a column without a zone, the OpenAPI Format Registry has `date-time-local`, RFC 3339 without the offset.
