Api Designのロゴ

Api Design

コミュニティ
wshaddix
api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, versioning, naming conventions, parameter ordering, and return types for NuGet packages and distributed systems. Use when designing public APIs for NuGet packages or libraries, making changes to existing public APIs, planning wire format changes for distributed systems, or reviewing pull requests for breaking changes.

概要

公開者wshaddix
リポジトリdotnet-skills
スキル名api-design
スター
79
フォーク
13
同梱ファイル
指示のみ
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    wshaddixがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルApi DesignをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/wshaddix/dotnet-skills/tree/master/skills/csharp-api-design
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wshaddix/dotnet-skills.git /tmp/dotnet-skills
mkdir -p .claude/skills
cp -r /tmp/dotnet-skills/skills/csharp-api-design .claude/skills/api-design
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでApi Designを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にApi Designを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Api Designは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

Public API Design and Compatibility

When to Use This Skill

Use this skill when:

  • Designing public APIs for NuGet packages or libraries
  • Making changes to existing public APIs
  • Planning wire format changes for distributed systems
  • Implementing versioning strategies
  • Reviewing pull requests for breaking changes

The Three Types of Compatibility

TypeDefinitionScope
API/SourceCode compiles against newer versionPublic method signatures, types
BinaryCompiled code runs against newer versionAssembly layout, method tokens
WireSerialized data readable by other versionsNetwork protocols, persistence formats

Breaking any of these creates upgrade friction for users.


Extend-Only Design

The foundation of stable APIs: never remove or modify, only extend.

Three Pillars

  1. Previous functionality is immutable - Once released, behavior and signatures are locked
  2. New functionality through new constructs - Add overloads, new types, opt-in features
  3. Removal only after deprecation period - Years, not releases

Benefits

  • Old code continues working in new versions
  • New and old pathways coexist
  • Upgrades are non-breaking by default
  • Users upgrade on their schedule

Naming Conventions for API Surface

Type Naming

Type KindSuffix PatternExample
Base classBase suffix only for abstract base typesValidatorBase
InterfaceI prefixIWidgetFactory
ExceptionException suffixWidgetNotFoundException
AttributeAttribute suffixRequiredPermissionAttribute
Event argsEventArgs suffixWidgetCreatedEventArgs
Options/configOptions suffixWidgetServiceOptions
BuilderBuilder suffixWidgetBuilder

Method Naming

PatternConventionExample
SynchronousVerb or verb phraseCalculate(), GetWidget()
AsynchronousAsync suffixCalculateAsync(), GetWidgetAsync()
Boolean queryIs/Has/Can prefixIsValid(), HasPermission()
Try patternTry prefix, out parameterTryGetWidget(int id, out Widget widget)
FactoryCreate prefixCreateWidget(), CreateWidgetAsync()
ConversionTo/From prefixToDto(), FromEntity()

Avoid Abbreviations in Public API

csharp
// WRONG -- abbreviations in public surface
public IReadOnlyList<TxnResult> GetRecentTxns(int cnt);

// CORRECT -- spelled out for clarity
public IReadOnlyList<TransactionResult> GetRecentTransactions(int count);

Parameter Ordering

Consistent parameter ordering reduces cognitive load.

Standard Order

  1. Target/subject -- the primary entity being operated on
  2. Required parameters -- essential inputs without defaults
  3. Optional parameters -- inputs with sensible defaults
  4. Cancellation token -- always last (convention enforced by CA1068)
csharp
public Task<Widget> GetWidgetAsync(
    int widgetId,                              // 1. Target
    WidgetOptions options,                     // 2. Required
    bool includeHistory = false,               // 3. Optional
    CancellationToken cancellationToken = default); // 4. Always last

Overload Progression

csharp
// Simple -- sensible defaults
public Task<Widget> GetWidgetAsync(int widgetId,
    CancellationToken cancellationToken = default)
    => GetWidgetAsync(widgetId, WidgetOptions.Default, cancellationToken);

// Detailed -- full control
public Task<Widget> GetWidgetAsync(int widgetId,
    WidgetOptions options,
    CancellationToken cancellationToken = default);

Return Type Selection

When to Return What

ScenarioReturn TypeRationale
Single entity, always existsWidgetThrow if not found
Single entity, may not existWidget?Nullable communicates optionality
Collection, possibly emptyIReadOnlyList<Widget>Immutable, indexable, communicates no mutation
Streaming resultsIAsyncEnumerable<Widget>Avoids buffering entire result set
Operation result with detailResult<Widget> / discriminated unionRich error info without exceptions
Void with asyncTaskNever async void except event handlers
Frequently synchronous completionValueTask<Widget>Avoids Task allocation on cache hits

Prefer IReadOnlyList Over IEnumerable

csharp
// WRONG -- caller does not know if result is materialized or lazy
public IEnumerable<Widget> GetWidgets();

// CORRECT -- signals materialized, indexable collection
public IReadOnlyList<Widget> GetWidgets();

// CORRECT -- signals streaming/lazy evaluation explicitly
public IAsyncEnumerable<Widget> GetWidgetsStreamAsync(
    CancellationToken cancellationToken = default);

The Try Pattern

csharp
public bool TryGetWidget(int widgetId, [NotNullWhen(true)] out Widget? widget);

public Task<Widget?> TryGetWidgetAsync(int widgetId,
    CancellationToken cancellationToken = default);

Error Reporting Strategies

Exception Hierarchy

csharp
public class WidgetServiceException : Exception
{
    public WidgetServiceException(string message) : base(message) { }
    public WidgetServiceException(string message, Exception inner) : base(message, inner) { }
}

public class WidgetNotFoundException : WidgetServiceException
{
    public int WidgetId { get; }
    public WidgetNotFoundException(int widgetId)
        : base($"Widget {widgetId} not found.") => WidgetId = widgetId;
}

public class WidgetValidationException : WidgetServiceException
{
    public IReadOnlyList<string> Errors { get; }
    public WidgetValidationException(IReadOnlyList<string> errors)
        : base("Widget validation failed.") => Errors = errors;
}

When to Use Exceptions vs Return Values

ApproachWhen to Use
Throw exceptionUnexpected failures, programming errors, infrastructure failures
Return null / default"Not found" is a normal, expected outcome
Try pattern (bool + out)Parsing or validation where failure is common and synchronous
Result objectMultiple failure modes that callers need to distinguish

Argument Validation

csharp
public Widget CreateWidget(string name, decimal price)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(name);
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(price);

    return new Widget(name, price);
}

API Change Guidelines

Safe Changes (Any Release)

csharp
// ADD new overloads with default parameters
public void Process(Order order, CancellationToken ct = default);

// ADD new optional parameters to existing methods
public void Send(Message msg, Priority priority = Priority.Normal);

// ADD new types, interfaces, enums
public interface IOrderValidator { }
public enum OrderStatus { Pending, Complete, Cancelled }

// ADD new members to existing types
public class Order
{
    public DateTimeOffset? ShippedAt { get; init; }  // NEW
}

Unsafe Changes (Never or Major Version Only)

csharp
// REMOVE or RENAME public members
public void ProcessOrder(Order order);  // Was: Process()

// CHANGE parameter types or order
public void Process(int orderId);  // Was: Process(Order order)

// CHANGE return types
public Order? GetOrder(string id);  // Was: public Order GetOrder()

// CHANGE access modifiers
internal class OrderProcessor { }  // Was: public

// ADD required parameters without defaults
public void Process(Order order, ILogger logger);  // Breaks callers!

Deprecation Pattern

csharp
// Step 1: Mark as obsolete with version
[Obsolete("Obsolete since v1.5.0. Use ProcessAsync instead.")]
public void Process(Order order) { }

// Step 2: Add new recommended API
public Task ProcessAsync(Order order, CancellationToken ct = default);

// Step 3: Remove in next major version

Extension Points

Interface-Based Extension

csharp
// GOOD -- interface-based extension point
public interface IWidgetValidator
{
    ValueTask<bool> ValidateAsync(Widget widget, CancellationToken ct = default);
}

// GOOD -- delegate-based extension for simple hooks
public class WidgetServiceOptions
{
    public Func<Widget, CancellationToken, ValueTask>? OnWidgetCreated { get; set; }
}

Extension Method Guidelines

GuidelineRationale
Place extensions in the same namespace as the typeDiscoverable without extra using statements
Never put extensions in System or System.LinqNamespace pollution
Prefer instance methods over extensions when you own the typeExtensions are a last resort
Keep the this parameter as the most specific usable typeAvoids polluting IntelliSense

Wire Compatibility

For distributed systems, serialized data must be readable across versions.

Requirements

DirectionRequirement
BackwardOld writers → New readers
ForwardNew writers → Old readers

Both are required for zero-downtime rolling upgrades.

Safely Evolving Wire Formats

Phase 1: Add read-side support

csharp
public sealed record HeartbeatV2(
    Address From,
    long SequenceNr,
    long CreationTimeMs);  // NEW field

public object Deserialize(byte[] data, string manifest) => manifest switch
{
    "Heartbeat" => DeserializeHeartbeatV1(data),
    "HeartbeatV2" => DeserializeHeartbeatV2(data),
    _ => throw new NotSupportedException()
};

Phase 2: Enable write-side (next minor version)

csharp
akka.cluster.use-heartbeat-v2 = on

Defensive Serialization Design

csharp
public sealed class WidgetDto
{
    [JsonPropertyName("id")]
    public int Id { get; init; }

    [JsonPropertyName("name")]
    public required string Name { get; init; }

    [JsonPropertyName("category")]
    public string? Category { get; init; }

    [JsonPropertyName("priority")]
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public int Priority { get; init; }
}

Enum Serialization Strategy

csharp
// GOOD -- string serialization is rename-safe
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum WidgetStatus
{
    Draft,
    Active,
    Archived
}

// RISKY -- integer serialization breaks when members are reordered
public enum WidgetPriority
{
    Low = 0,
    Medium = 1,
    High = 2
}

API Approval Testing

Prevent accidental breaking changes with automated API surface testing.

csharp
[Fact]
public Task ApprovePublicApi()
{
    var api = typeof(MyLibrary.PublicClass).Assembly.GeneratePublicApi();
    return Verify(api);
}

PR Review Process

  1. PR includes changes to *.verified.txt files
  2. Reviewers see exact API surface changes in diff
  3. Breaking changes are immediately visible
  4. Conscious decision required to approve

Versioning Strategy

Semantic Versioning (Practical)

VersionChanges Allowed
Patch (1.0.x)Bug fixes, security patches
Minor (1.x.0)New features, deprecations, obsolete removal
Major (x.0.0)Breaking changes, old API removal

Key Principles

  1. No surprise breaks - Even major versions should be announced
  2. Extensions anytime - New APIs can ship in any release
  3. Deprecate before remove - [Obsolete] for at least one minor version
  4. Communicate timelines - Users need to plan upgrades

Pull Request Checklist

  • No removed public members (use [Obsolete] instead)
  • No changed signatures (add overloads instead)
  • No new required parameters (use defaults)
  • API approval test updated (.verified.txt changes reviewed)
  • Wire format changes are opt-in (read-side first)
  • Breaking changes documented (release notes, migration guide)

Anti-Patterns

Breaking Changes Disguised as Fixes

csharp
// "Bug fix" that breaks users
public async Task<Order> GetOrderAsync(OrderId id)  // Was sync!
{
}

// Correct: Add new method, deprecate old
[Obsolete("Use GetOrderAsync instead")]
public Order GetOrder(OrderId id) => GetOrderAsync(id).Result;

public async Task<Order> GetOrderAsync(OrderId id) { }

Silent Behavior Changes

csharp
// Changing defaults breaks users
public void Configure(bool enableCaching = true)  // Was: false!

// Correct: New parameter with new name
public void Configure(
    bool enableCaching = false,
    bool enableNewCaching = true)

Polymorphic Serialization

csharp
// AVOID: Type names in wire format
{ "$type": "MyApp.Order, MyApp", "Id": 123 }

// PREFER: Explicit discriminators
{ "type": "order", "id": 123 }

Agent Gotchas

  1. Do not use abbreviations in public API names -- spell out words.
  2. Do not place CancellationToken before optional parameters -- CA1068 enforces last.
  3. Do not return mutable collections from public APIs -- return IReadOnlyList<T>.
  4. Do not change serialized property names without [JsonPropertyName] annotations.
  5. Do not add required parameters to existing public methods -- add overload or use defaults.
  6. Do not use async void in API surface -- return Task or ValueTask.
  7. Do not design exception hierarchies without a base library exception.
  8. Do not put extension methods in the System namespace.

Resources

よくある質問

AIスキル「Api Design」では何ができますか?

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, versioning, naming conventions, parameter ordering, and return types for NuGet packages and distributed systems. Use when designing public APIs for NuGet packages or libraries, making changes to existing public APIs, planning wire format changes for distributed systems, or reviewing pull requests for breaking changes.

TypingMindでApi Designを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Api Designはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにApi Designをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/wshaddix/dotnet-skills/tree/master/skills/csharp-api-designを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Api Designを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Api Designは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもApi Designを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Api Design」は無料ですか?

wshaddixがGitHubで公開しています。ライセンス条件はリポジトリでご確認ください。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇