Skip to content

Model Generator

Arun Prakash edited this page Nov 3, 2026 · 1 revision

Model Generator

dart run wordpress_client:generate reads the JSON schema WordPress publishes for a route and writes Dart model classes for it, ready for client.resource<T>.

dart run wordpress_client:generate \
  --site https://example.com \
  --route wp/v2/events \
  --out lib/models/event.dart
import 'models/event.dart';

final events = client.resource<Event>('events', decoder: Event.fromJson);
final upcoming = (await events.list()).dataOrThrow();
print(upcoming.first.title?.rendered);

Options

Option
--site <url> Site URL (https://example.com) or REST root (.../wp-json)
--route <route> Route to read, e.g. wp/v2/events. Repeat for several; all classes go into one file
--schema <file> Read a saved OPTIONS answer or bare schema instead of a site
--name <Class> Class name, only with a single route or schema. Default: from the schema title (event gives Event)
--out <file> Output file. Default: standard output
--user, --app-password For routes that need authentication. WP_USERNAME and WP_APP_PASSWORD are read from the environment too
--help All options

Prefer the environment variables over --app-password, so the password does not end up in your shell history.

What you get

For each route, a class that:

  • implements ISelfRepresentative, so self, metaValue, acfValue and the other model helpers work;
  • has one nullable field per schema property, since WordPress leaves fields out depending on context and _fields;
  • converts values leniently ('12' as int, '1' as bool, ISO strings as DateTime);
  • has nested classes for object properties (EventTitle for title), lists of the right type, and Map<String, dynamic> for free-form objects;
  • has fromJson and toJson (only the fields that are set);
  • carries the schema descriptions as doc comments and marks read-only fields.

Property names become camelCase Dart names; Dart keywords get a Value suffix (default becomes defaultValue) and clashes get a number.

Without network access

Save the schema once and generate from the file, for example in CI:

curl -X OPTIONS https://example.com/wp-json/wp/v2/events > event.schema.json
dart run wordpress_client:generate --schema event.schema.json --out lib/models/event.dart

Regenerating

The output file starts with a "Generated" comment and is overwritten on every run. Keep custom code in an extension or a wrapper, not in the generated file. Re-run the generator after adding fields or plugins on the site.

Clone this wiki locally