State Provider logo

State Provider

Organization
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'.

Overview

Publisherapi-platform
Repositoryskillset
Skill namestate-provider
Stars
29
Forks
1
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by api-platform on GitHub. Read the source before you install it.

Installation

Install the State Provider AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/api-platform/skillset/tree/main/skills/state-provider
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable State Provider in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads State Provider on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so State Provider is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

Frequently asked questions

What does the State Provider AI skill do?

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'.

Why use State Provider on TypingMind?

Because you install it once and use it with any model. State Provider is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install State Provider in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/api-platform/skillset/tree/main/skills/state-provider. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use State Provider?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with State Provider?

As many as you like. As long as a model supports skills, you can use State Provider with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the State Provider AI skill free?

It is published on GitHub by api-platform. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇