tonik 0.11.1
tonik: ^0.11.1 copied to clipboard
Pure Dart OpenAPI 3.0/3.1 code generator. Creates type-safe API client packages for Dart and Flutter with sealed classes, pattern matching, and full encoding support.
Tonik #
A Dart code generator for OpenAPI 3.0 and 3.1 specifications, with partial OpenAPI 3.2 support.
Generate type-safe API client packages for Dart and Flutter. Tonik produces idiomatic code with sealed classes for oneOf, exhaustive pattern matching for responses, and support for common OpenAPI parameter and body encodings. See the support matrix for current capabilities and limitations.
Key Features #
Type-Safe Response Handling by Status Code and Content Type #
Most OpenAPI generators pick a single "success" type and a single "error" type per operation, silently discarding the response schemas for all other status codes. If your endpoint returns a Pet for 200, a ValidationError for 400, and a NotFoundError for 404, you only get the 200 type — the rest are lost or reduced to untyped error strings.
Tonik generates a distinct type for every response defined in your spec. Each status code and content type combination becomes its own strongly-typed class, and the compiler enforces exhaustive handling:
final response = await petApi.updatePet(body: pet);
switch (response) {
case TonikSuccess(:final value):
switch (value) {
case UpdatePetResponse200(:final body):
print('Updated: ${body.name}');
case UpdatePetResponse400(:final body):
print('Validation: ${body.message}');
case UpdatePetResponse404(:final body):
print('Not found: ${body.detail}');
}
case TonikError(:final error):
print('Network error: $error');
}
Every response body is deserialized into the correct type for its status code — no casting, no type checks, no lost information. Add a new response to your spec, regenerate, and the compiler tells you every call site that needs updating.
Composition with Sealed Classes #
oneOf, anyOf, and allOf generate idiomatic Dart code:
oneOf- Sealed class with one subclass per variantanyOf- Class with nullable fields for each alternativeallOf- Class with a field for each member schema
See Composite Data Types for usage examples.
No Name Conflicts #
Use Error, Response, List, or any Dart built-in as schema names. Tonik uses scoped code emission to properly qualify all type references - no naming collisions with dart:core or transport dependencies.
Integer and String Enums #
Both work out of the box, with optional unknown-value handling for forward compatibility:
status:
type: integer
enum: [0, 1, 2]
x-dart-enum: [pending, active, closed]
All Parameter Encoding Styles #
Path, query, and header parameters support all OpenAPI styles: simple, label, matrix, form, spaceDelimited, pipeDelimited, and deepObject.
Pure Dart #
Install with dart pub global activate tonik and run. No JVM, no Docker, no external dependencies.
Choice of HTTP Backend #
Generate clients with Dio (the default) or package:http. Selection is
generation-time and applies to the whole generated package; ordinary models,
API calls, and result handling keep the same shape.
Platform Support #
Generated packages are pure Dart with no native plugin dependency. They support native Dart and browsers.
Documentation #
- Features Overview – Complete feature reference
- HTTP Backends – Backend selection, client ownership, and migration
- Streaming Responses – Typed NDJSON, JSONL, JSON-seq, and SSE streams, cancellation, and browser behavior
- Configuration –
tonik.yamloptions, name overrides, filtering - Data Types – OpenAPI to Dart type mappings
- Composite Data Types –
oneOf,anyOf,allOfusage - Defaults –
defaultkeyword handling and generated constants - Additional Properties –
additionalPropertiessupport and pure maps - Multipart –
multipart/form-datarequest bodies - Authentication – Dio interceptors and
http.Clientwrappers - URI Encoding – query/body encoding and
allowReserved
Quick Start #
Install #
dart pub global activate tonik
Generate #
tonik --package-name=my_api --spec=openapi.yaml
Use #
Add the generated package to your project:
dart pub add my_api:{'path':'./my_api'}
dart pub add tonik_util
Then import and use:
import 'package:my_api/my_api.dart';
import 'package:tonik_util/tonik_util.dart';
final api = PetApi(CustomServer(baseUrl: 'https://api.example.com'));
final response = await api.getPetById(petId: 1);
switch (response) {
case TonikSuccess(:final value):
print('Response: $value');
case TonikError(:final error):
print('Failed: $error');
}
See the real server examples for Dart clients using FastAPI, NestJS, Fastify, Spring Boot, and Rails APIs.
Feature Summary #
| Category | What's Supported |
|---|---|
| Responses | Multiple status codes, multiple content types and media-type ranges (type/*, */*), response headers, default and range codes (2XX) |
| Streaming Responses | Typed NDJSON, JSONL, JSON-seq, and SSE response streams with explicit itemSchema |
| Composition | oneOf (sealed classes), anyOf, allOf, discriminators, nested composition |
| Types | Integer/string enums, date, date-time with timezone, decimal/BigDecimal, uri, binary |
| Parameters | Path, query, header, cookie; supported encoding styles include form, simple, label, matrix, and deepObject |
| Request Bodies | application/json, application/x-www-form-urlencoded, application/octet-stream, text/plain |
| Multipart | multipart/form-data with primitive, file, JSON, and array parts; per-part encoding and content types |
| Schema | readOnly/writeOnly enforcement, nullable, required, deprecated, boolean schemas, additionalProperties |
| Configuration | HTTP backend selection, name overrides, filtering by tag/operation/schema, deprecation handling, content-type mapping, parallel generation tuning |
| OAS 3.1 | $ref with siblings, $defs local definitions, boolean schemas, nullable type arrays, contentEncoding/contentMediaType |
OpenAPI 3.2 support includes typed itemSchema response streams, local reusable Media Type Objects under components.mediaTypes, and inline dataValue examples. See Features for details.
Acknowledgments #
Special thanks to felixwoestmann, without whom this project would not exist.