본문으로 건너뛰기
cccskills
무료GitHub에 공개

implementing-openapi-in-dart

Reads an OpenAPI 3.0 specification and manually implements a type-safe Dart API layer using Dio for HTTP, Freezed or Equatable for models, and json_serializable for serialisation. Use when given an OpenAPI/Swagger file (JSON or YAML) and asked to implement the API in Flutter/Dart, create Dart models from an API schema, build a Dio API client, implement endpoints from a spec, convert openapi to dart, or set up a data/network layer from an API contract. Handles $ref resolution, oneOf union types, enums, query params, request bodies, and DioException error mapping.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md8.2 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Implementing OpenAPI 3.0 in Dart

Given an OpenAPI 3.0 spec, implement a type-safe Dart API layer with:

  • Freezed (or Equatable) for models
  • Dio for HTTP with interceptors and error handling
  • json_serializable for JSON serialisation

Process

  1. Read the OpenAPI spec — parse components/schemas for models, paths for endpoints.
  2. Map schemas → Dart models (Freezed or Equatable — see Model Strategy).
  3. Map paths → Dio service methods.
  4. Add a repository layer that wraps the service.
  5. Wire error handling via DioException → domain ApiError.

Dependencies

dependencies:
  dio: ^5.9.2
  freezed_annotation: ^3.1.0   # if using Freezed
  json_annotation: ^4.11.0
  equatable: ^2.0.5             # if using Equatable

dev_dependencies:
  build_runner: ^2.14.1
  freezed: ^3.2.5               # if using Freezed
  json_serializable: ^6.13.1

Directory Structure

lib/
└── data/
    ├── network/
    │   ├── dio_client.dart          # Dio instance + interceptors
    │   ├── api_error.dart           # global error model
    │   └── services/
    │       └── product_service.dart # one file per resource tag
    └── models/
        ├── product.dart
        └── ...

Dio Client Setup

import 'package:dio/dio.dart';

Dio createDioClient({required String baseUrl, String? accessToken}) {
  final dio = Dio(BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: const Duration(seconds: 10),
    receiveTimeout: const Duration(seconds: 10),
    headers: {'Content-Type': 'application/json'},
  ));

  dio.interceptors.add(InterceptorsWrapper(
    onRequest: (options, handler) {
      if (accessToken != null) {
        options.headers['Authorization'] = 'Bearer $accessToken';
      }
      handler.next(options);
    },
    onError: (error, handler) {
      // Convert DioException to domain ApiError before propagating
      handler.next(error);
    },
  ));

  return dio;
}

Model Strategy

Use casePackageWhen
Needs copyWith, pattern matching, union types (oneOf)FreezedComplex domain models
Only needs value equality (== / hashCode)EquatableSimple request/response DTOs

Freezed Model (complex / union types)

// OpenAPI: components/schemas/Product
import 'package:freezed_annotation/freezed_annotation.dart';

part 'product.freezed.dart';
part 'product.g.dart';

@freezed
sealed class Product with _$Product {
  const factory Product({
    required String id,
    required String title,
    required double price,
    @JsonKey(name: 'created_at') DateTime? createdAt, // snake_case from spec
  }) = _Product;

  factory Product.fromJson(Map<String, dynamic> json) =>
      _$ProductFromJson(json);
}

Equatable Model (simple DTO)

// OpenAPI: components/schemas/CreateProductRequest
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';

part 'create_product_request.g.dart';

@JsonSerializable()
class CreateProductRequest extends Equatable {
  const CreateProductRequest({required this.title, required this.price});

  final String title;
  final double price;

  Map<String, dynamic> toJson() => _$CreateProductRequestToJson(this);

  @override
  List<Object?> get props => [title, price];
}

Type Mapping

Primitives

OpenAPIDart
stringString
integerint
numberdouble
booleanbool
string / format: date-timeDateTime
string / format: uuidString
string / format: uriUri

Nullability

  • Property in required array → non-nullable (String id)
  • Property NOT in required → nullable (String? name)

Enum

// OpenAPI: type: string, enum: [active, draft, archived]
@JsonEnum(fieldRename: FieldRename.snake)
enum ProductStatus { active, draft, archived }

oneOf / Union Types → Freezed sealed

// OpenAPI: oneOf: [{$ref: Cat}, {$ref: Dog}]
@freezed
sealed class Pet with _$Pet {
  const factory Pet.cat(Cat data) = _PetCat;
  const factory Pet.dog(Dog data) = _PetDog;

  factory Pet.fromJson(Map<String, dynamic> json) => _$PetFromJson(json);
}

// Exhaustive pattern matching at the call site:
switch (pet) {
  case Pet(:final cat): ...
  case Pet(:final dog): ...
}

$ref Resolution

{"$ref": "#/components/schemas/Product"} → use Product class directly. Never inline duplicate definitions.


Service Layer (Dio)

One service class per OpenAPI tag. Method signatures follow: {httpMethod}{Resource}.

// Covers: GET /products, POST /products, GET /products/{id}
class ProductService {
  const ProductService(this._dio);
  final Dio _dio;

  Future<List<Product>> getProducts({int page = 1, int limit = 20}) async {
    final response = await _dio.get<List<dynamic>>(
      '/products',
      queryParameters: {'page': page, 'limit': limit},
    );
    return response.data!.map((e) => Product.fromJson(e as Map<String, dynamic>)).toList();
  }

  Future<Product> getProduct(String id) async {
    final response = await _dio.get<Map<String, dynamic>>('/products/$id');
    return Product.fromJson(response.data!);
  }

  Future<Product> createProduct(CreateProductRequest request) async {
    final response = await _dio.post<Map<String, dynamic>>(
      '/products',
      data: request.toJson(),
    );
    return Product.fromJson(response.data!);
  }
}

Error Handling

Define a global error model matching the spec's error schema:

@freezed
sealed class ApiError with _$ApiError {
  const factory ApiError({
    required int status,
    required String message,
    String? detail,
  }) = _ApiError;

  factory ApiError.fromJson(Map<String, dynamic> json) =>
      _$ApiErrorFromJson(json);
}

Wrap Dio calls in the repository to catch DioException:

class ProductRepository {
  const ProductRepository(this._service);
  final ProductService _service;

  Future<List<Product>> fetchProducts({int page = 1}) async {
    try {
      return await _service.getProducts(page: page);
    } on DioException catch (e) {
      if (e.response?.data != null) {
        throw ApiError.fromJson(e.response!.data as Map<String, dynamic>);
      }
      rethrow;
    }
  }
}

Naming Conventions

OpenAPI elementDart name
components/schemas/ProductItemclass ProductItem
POST /products request bodyCreateProductRequest
GET /products responseList<Product> or typedef GetProductsResponse = List<Product>
snake_case JSON key@JsonKey(name: 'snake_case') on camelCase field

Constraints

  • No ! operator: rely on nullability — if spec says required, make it non-nullable.
  • Never duplicate $ref schemas: reference the class; do not inline.
  • Use @JsonKey(name: ...) for naming mismatches — do not rename the JSON key, rename the Dart field.
  • Equatable vs Freezed: default to Freezed for domain models; use Equatable for pure request DTOs that don't need copyWith.
  • DioException always caught at repository level — services throw raw, repositories map to ApiError.
  • Run dart run build_runner build --delete-conflicting-outputs after generating models.

Old Patterns (pre-Freezed 3)

Freezed 2.x used abstract class instead of sealed class. Both patterns still work, but prefer sealed for exhaustive pattern matching with Dart 3.

# Freezed 2.x (no longer recommended)
dependencies:
  freezed_annotation: ^2.4.1

dev_dependencies:
  freezed: ^2.5.2

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Declarative animation patterns using flutter_animate v4.5.x with composable effects (fade, scale, slide, shimmer, shake, blur), GLSL fragment shaders, and scroll-synchronized animations. Use this skill for adding UI animations and transitions, building staggered or sequenced effects, creating custom animation effects, fixing animation jank or performance issues, implementing shimmer loading states, or adding scroll-driven animations. Supports delays, curves, adaptive effects, and easy extension method chaining (.animate()).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Dart 3 modern features (through 3.10) and Effective Dart best practices including records, patterns, sealed classes, dot shorthands, null-aware collection elements, and wildcard variables. Use when adopting Dart 3.7+ syntax, using dot shorthands for enums or static members, using null-aware elements in lists or maps, using wildcard _ parameters, improving code quality, or reviewing Dart code conventions.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Expert-level guidance for Flutter production applications: architecture decisions (Clean/Layered/Hexagonal/Feature-First), advanced state management (BLoC/Riverpod/GetX), performance optimization (eliminating jank, memory profiling, reducing rebuild overhead), code review with design pattern enforcement, scalability assessments, native platform integration (MethodChannel/EventChannel/FFI), complex UI challenges (custom render objects, slivers), testing strategies (unit/widget/integration/golden), CI/CD pipeline architecture, build optimization, and accessibility compliance. Triggers: 'architecture decision', 'design pattern', 'performance issue', 'code review', 'production problem', 'scaling concerns', 'best practices', 'technical debt', 'refactoring strategy'. Essential for complex enterprise apps, critical production debugging, architectural refactors, or when choosing between competing technical approaches.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Builds SEO-friendly web applications with Dart using the Jaspr framework. Use when creating Dart-based websites, blogs, or landing pages requiring semantic HTML output; implementing server-side rendering (SSR) or static site generation (SSG); adding Tailwind CSS via jaspr_tailwind; routing with jaspr_router; testing components with jaspr_test; or building full-stack Dart web apps where Flutter Web's canvas rendering is unsuitable.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

shadcn_flutter UI component library for building accessible, themed Flutter interfaces. Use when integrating shadcn components, configuring design system theming, or building consistent widget layouts.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Configures Codemagic CI/CD pipelines for Flutter using `codemagic.yaml`. Use when setting up automated Flutter builds on Codemagic, configuring iOS code signing without Fastlane Match, deploying to App Store Connect or Google Play from Codemagic, caching pub dependencies in Codemagic, setting up encrypted environment variable groups, running tests with Codemagic's test dashboard, or choosing between Codemagic and GitHub Actions + Fastlane for a Flutter CI/CD pipeline.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Poorgramer-Zack의 스킬 모두 보기

이 스킬의 문제 신고