State Providerのロゴ

State Provider

組織
api-platform
state-provider

Creates state providers for read operations in API Platform — the read/Query side of its CQRS-style provider/processor split. Use whenever GET data needs custom retrieval or shaping — computed or enriched fields, transforming entities to different DTOs, decorating built-in Doctrine providers, sortable computed fields via repositoryMethod — or any 'the response should also include X' request, or to understand when a provider runs vs a processor (the read vs write phase), even if the user doesn't say 'provider'.

概要

公開者api-platform
リポジトリskillset
スキル名state-provider
スター
29
フォーク
1
同梱ファイル
指示のみ
リンク
  • Markdown形式の指示

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

  • どのLLMでも利用可能

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

  • 指示だけで完結

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

  • オープンソース

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

インストール

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

1

TypingMindにインストール

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

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

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

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

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

TypingMindで使用

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

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

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

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

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

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

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

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

スキルの指示

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

Creating State Providers

State Providers retrieve data for read operations (Get, GetCollection) — the read phase of an operation, the Query side of API Platform's CQRS-style split (a state-processor handles the Command/write side).

A provider runs when the operation's read flag is true. You normally leave it unset and API Platform resolves it from the request: read defaults to "the operation has URI variables, or the HTTP method is safe", and write (the processor) to "the method is not safe".

Operationprovider runs (read)processor runs (write)
Get (item) / GetCollectionyesno
Post (collection)no (no URI vars, unsafe)yes
Put, Patch, Delete (item)yesyes

Override the flag to decouple the phase from the verb: read: false skips the built-in fetch on an item write (upsert), and write: true runs a processor on a Get (see state-processor). See operations → Read & write phases for the full read → deserialize → validate → write → serialize lifecycle.

Basic Structure

php
<?php
namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\State\ProviderInterface;

/**
 * @implements ProviderInterface<YourResource|null>
 */
final class YourResourceProvider implements ProviderInterface
{
    public function provide(
        Operation $operation,
        array $uriVariables = [],
        array $context = []
    ): object|array|null {
        if ($operation instanceof CollectionOperationInterface) {
            return $this->repository->findAll();
        }

        return $this->repository->find($uriVariables['id']);
    }
}

Decorating Built-in Providers

Wrap the default provider to add custom logic (computed fields, enrichment):

php
<?php
namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

final class EnrichedItemProvider implements ProviderInterface
{
    public function __construct(
        #[Autowire(service: 'api_platform.doctrine.orm.state.item_provider')]
        private ProviderInterface $itemProvider,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?object
    {
        $data = $this->itemProvider->provide($operation, $uriVariables, $context);

        if (null === $data) {
            return null; // API Platform returns 404 automatically
        }

        // Enrich with computed fields
        $data->computedScore = $this->computeScore($data);

        return $data;
    }
}

Doctrine service names

PersistenceItem ProviderCollection Provider
ORMapi_platform.doctrine.orm.state.item_providerapi_platform.doctrine.orm.state.collection_provider
MongoDB ODMapi_platform.doctrine_mongodb.odm.state.item_providerapi_platform.doctrine_mongodb.odm.state.collection_provider

Laravel (Eloquent): ProviderInterface is identical and resources reference a provider by class-string (provider: YourProvider::class). There are no api_platform.doctrine.* service ids — the built-in Eloquent providers are bound in the container by their class name (ApiPlatform\Laravel\Eloquent\State\ItemProvider / …\State\CollectionProvider). To decorate one, type-hint that concrete class in your constructor (the container resolves it). Stable scalar/computed-field sorting uses stateOptions: new Options(modelClass: …) on the Eloquent Options and an OrderFilter parameter rather than repositoryMethod.

Enriching Paginated Collections

Iterate over paginated results to add computed fields:

php
use ApiPlatform\State\Pagination\PaginatorInterface;

final class MailboxListProvider implements ProviderInterface
{
    public function __construct(
        #[Autowire(service: 'api_platform.doctrine_mongodb.odm.state.collection_provider')]
        private ProviderInterface $collectionProvider,
        private MailboxHelper $helper,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): PaginatorInterface
    {
        $mailboxes = $this->collectionProvider->provide($operation, $uriVariables, $context);

        foreach ($mailboxes as $item) {
            $item->totalMessages = $this->helper->countMessages($item->getId());
        }

        return $mailboxes;
    }
}

Cross-Resource Providers (Returning a Different Type)

A provider can fetch one resource type and return another:

php
final class RawMessageProvider implements ProviderInterface
{
    public function __construct(
        #[Autowire(service: 'api_platform.doctrine_mongodb.odm.state.item_provider')]
        private ProviderInterface $itemProvider,
        private RawMessageBuilderInterface $builder,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?RawMessage
    {
        // Fetch the Document\Message using Doctrine
        $message = $this->itemProvider->provide($operation, $uriVariables, $context);
        if (!$message) {
            return null;
        }

        // Transform to a completely different API resource
        $raw = new RawMessage();
        $raw->id = $message->getId();
        $raw->content = $this->builder->build($message);
        return $raw;
    }
}

Provider Parameters

  • $operation: Metadata about the operation (Get, GetCollection, etc.)
  • $uriVariables: URI path variables (e.g., ['id' => '123', 'accountId' => '456'])
  • $context: Additional context:
    • request: The Symfony HttpFoundation Request
    • resource_class: The API resource class
    • filters: Applied query parameter filters

Assigning to Resource

php
#[Get(provider: YourProvider::class)]
#[GetCollection(provider: YourCollectionProvider::class)]
class YourResource {}

Computed / Sortable Fields via a Repository Method (Doctrine)

When a field is a SQL aggregate that must also be sortable in the database, a plain provider can't help — sorting happens in the query. The cleanest way is to point the built-in Doctrine provider at a custom repository method that returns a QueryBuilder, via stateOptions (API Platform 4.4+). The provider runs your query builder, then layers pagination, filters and link handlers on top of it.

php
// Repository: return a QueryBuilder, not results
class CartRepository extends EntityRepository
{
    public function getCartsWithTotalQuantity(): QueryBuilder
    {
        return $this->createQueryBuilder('o')
            ->leftJoin('o.items', 'items')
            ->addSelect('COALESCE(SUM(items.quantity), 0) AS totalQuantity')
            ->addGroupBy('o.id');
    }
}
php
use ApiPlatform\Doctrine\Orm\State\Options;

#[ORM\Entity(repositoryClass: CartRepository::class)]
#[GetCollection(
    stateOptions: new Options(repositoryMethod: 'getCartsWithTotalQuantity'),
    processor: [self::class, 'process'],
    write: true,
    parameters: [
        'sort[:property]' => new QueryParameter(filter: new SortFilter(), properties: ['totalQuantity']),
    ],
)]
class Cart
{
    public int|string|null $totalQuantity;

    // A non-HIDDEN scalar addSelect makes rows arrive as [entity, 'totalQuantity' => N].
    // Flatten them back onto the entity with a processor:
    public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
    {
        foreach ($data as &$value) {
            $cart = $value[0];
            $cart->totalQuantity = $value['totalQuantity'] ?? 0;
            $value = $cart;
        }

        return $data;
    }
}

Use a Doctrine collection extension (see securing-collections) instead when the query change must apply to every operation/query for the resource (e.g. multi-tenant isolation). repositoryMethod scopes one operation's base query; an extension mutates them all.

Per-Property Serialization Context

Embed the same related resource at different depths by switching the normalization group on one property with #[Context]:

php
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Attribute\Groups;

#[ApiResource(normalizationContext: ['groups' => ['initial']])]
class Order
{
    #[Groups(['initial'])]
    public ?Customer $customer = null;

    #[Groups(['initial'])]
    #[Context(['normalization' => ['groups' => ['summary']]])]
    public ?Customer $billedTo = null; // serialized with the 'summary' group only
}

Best Practices

  1. Return null for missing items — API Platform handles the 404
  2. Use CollectionOperationInterface to distinguish collection vs item
  3. When decorating, always delegate to the built-in provider first
  4. For computed fields on collections, iterate over the paginator (it's lazy)
  5. For sortable computed fields, use stateOptions(repositoryMethod:) — not a provider

よくある質問

AIスキル「State Provider」では何ができますか?

Creates state providers for read operations in API Platform — the read/Query side of its CQRS-style provider/processor split. Use whenever GET data needs custom retrieval or shaping — computed or enriched fields, transforming entities to different DTOs, decorating built-in Doctrine providers, sortable computed fields via repositoryMethod — or any 'the response should also include X' request, or to understand when a provider runs vs a processor (the read vs write phase), even if the user doesn't say 'provider'.

TypingMindでState Providerを使うメリットは何ですか?

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

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

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

State Providerを使えるAIモデルはどれですか?

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

State Providerは何個のAIモデルで使えますか?

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

AIスキル「State Provider」は無料ですか?

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

AIスキルとは何ですか?

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

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

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

すべて見る

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

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