api-resource-development
Use when adding or changing a REST or GraphQL operation, a command, a query or an event subscriber inside one bounded context of a Rust axum service, covering the four request extractors, the problem-
Files1
View on GitHubSKILL.mdplugins/rust-backend-sdlc/skills/api-resource-development/SKILL.md
GitHubAPI Resource Development
Profile keys consumed
framework.http— the HTTP framework; a non-null value selects the REST steps, null skips themframework.openapi— true requires the OpenAPI annotation on every REST handler and the OpenAPI snapshot co-change; false drops bothframework.graphql— true selects the GraphQL section; false skips itpersistence.engine— a non-null value selects a database adapter behind the repository port; null means no database adapterarchitecture.composition_root— the crate that wires handlers, subscribers, adapters, routes and GraphQL roots; null stops the skillmake.generate_openapi_spec— the target that regenerates the OpenAPI snapshot in the same changemake.generate_graphql_spec— the target that regenerates the GraphQL snapshot in the same changemake.tests_with_coverage— the evidence target for unit and integration tests under the coverage floormake.e2e_tests— the evidence target for the end-to-end scenarios over HTTP
Repository precedence
Read .claude/skills/api-resource-development/SKILL.md and AGENTS.md first; they win. This skill adds only profile resolution, the evidence format, the bounded loop, the escalation block and the verdict line.
The repository skill holds the recipes for its own source tree (file names, module names, registration calls). Where its wording differs from the Steps below, follow the repository skill and write the difference into the precedence: line of the evidence; a precedence note is not a degrade note and does not change the verdict. When the repository skill is absent, the Steps below apply in full and the evidence records source: plugin instead of source: repo+plugin.
Context
- The service is a Rust workspace with one crate per layer per bounded context. The example context in this skill is
<group>/<context>with its three cratesdomain,applicationandinfrastructure, and the aggregate is<Entity>. Never copy the template's sample context names into new code. - Layer order is domain, then application, then infrastructure, then the wiring in the composition root named by
architecture.composition_root. A domain crate stays framework-free and I/O-free. - A REST handler and a GraphQL resolver call the same command or query, so a behaviour change reaches both contracts.
- The skill runs inside a loop stage (the implementation stage or the remediation step of the review stage) after the triage recorded
EXECUTEfor it, or directly when a person asks for an operation change. Snapshot validation, Spectral findings and the breaking-change policy belong to api-contract-development; migrations belong to database-migrations.
Task
Add or change one operation of <group>/<context> (a REST endpoint, a GraphQL field, a command, a query or an event subscriber) so that it follows the template's extractors, error model and ports, ships its regenerated contract snapshots in the same change, and is proven by the evidence targets. Report the result in the evidence format and end with the verdict line.
Success criteria
- Every new or changed REST handler takes its path, query and body only through
ApiPath,ValidatedQuery,ValidatedJsonorApiJson; no handler signature extracts with the bare axumPath,QueryorJson, whose rejections are plain text. - Every error path of a handler or resolver ends in a
Problemserved asapplication/problem+json; the context's application error enum converts intoProblemvariant by variant. - Every command returns no data: its handler result carries only success or the application error, and the caller reads the new state through a query.
- Every subscriber is idempotent: handling the same event twice leaves the same state, and no subscriber dispatches a command.
- Time, identifiers, storage and messaging are reached only through ports (
Clock,UuidGenerator, the repository port,EventBus); outside the adapters that implementClockandUuidGenerator, the change adds noSystemTime::now,Instant::noworUuid::new_v4. - Each regenerated contract snapshot is part of the same change as the code: the target mapped by
make.generate_openapi_specran whenframework.openapiis true, and the target mapped bymake.generate_graphql_specran whenframework.graphqlis true. - The targets-run list shows the targets mapped by
make.tests_with_coverageandmake.e2e_testsaspassed, or asnot run (<reason>)with a reason from the closed set. - The evidence block and the verdict line are printed.
Steps
Profile resolution
- Read the nine keys above from
.claude/rust-sdlc.yml. When the profile is missing or unreadable, stop with the escalation block andrecommended_action: run /rs-sdlc-setup on the default branch and commit the result. - Branch on each key before any edit:
architecture.composition_rootnull: no wiring point exists, so no new operation can be reached. Stop with the escalation block,blocking_finding: architecture.composition_root is null.framework.httpnon-null: run the REST operations steps. Null: skip them and recordSKIPPED: framework.http is null.framework.openapitrue: annotate every REST handler and regenerate the OpenAPI snapshot. False: no annotation; record the OpenAPI snapshot step asSKIPPED: framework.openapi is false.framework.graphqltrue: run the GraphQL section. False: skip it and recordSKIPPED: framework.graphql is false.persistence.enginenon-null: the repository port gets a database adapter in the infrastructure crate. Null: no database adapter and no migration; an operation that needs new storage stops with the escalation block,blocking_finding: persistence.engine is null.- Any of the four target keys above that is null: its target is recorded
not run (capability absent)with a degrade note; it is never replaced by a raw command.
Domain and application
- Read the existing slice of
<group>/<context>and copy its shape. In the domain crate add or change the aggregate<Entity>, its value objects, its domain error enum, its events and the repository port trait. See implementing-ddd-architecture for aggregates and ports. - A command: a struct that implements
CommandwithErrorset to the context's application error, and a handler that holds its ports asArc<dyn Port>, keeps the logic in an inherentasync fnand lets the#[async_trait]CommandHandlerimpl only delegate. The handler loads or creates one aggregate, saves it, then publishes the pulled domain events; a publication failure is logged per subscriber and never fails the command. The command returns no data: the caller generates the identifier through theUuidGeneratorport before the dispatch and reads the result through a query. - A query: the same shape with
Outputset to a view or a list of views. A query handler never mutates state and returns views, never aggregates. - An event subscriber: implements
DomainEventSubscriberfor one event, never dispatches a command, and is idempotent (an upsert keyed by the aggregate identifier or a check on the event identifier, never a blind insert). Delivery is at most once; when the story needs guaranteed delivery, stop with the escalation block,blocking_finding: guaranteed delivery needs an outbox, because adding an outbox is an architecture decision. - Error model: the context has one application error enum, and
impl From<...> for Problemmaps every variant explicitly; an invariant violation becomes the 422 problem of type/problems/validation-failedwith one entry inviolations[]per property. See rust-error-handling for the full error model.
REST operations
Run this subsection when framework.http is non-null; otherwise it is skipped as recorded in the profile resolution.
- Add the request DTO with serde and
Validateattributes (andToSchemawhenframework.openapiis true), and the response DTO. - Write the handler with these extractors only:
ApiPathfor path parameters,ValidatedQueryfor a query string with constraints,ValidatedJsonfor a body with constraints,ApiJsonfor a body without constraints. Their rejections are alreadyProblemdocuments. The handler returnsResult<_, Problem>. - When
framework.openapiis true, annotate the handler with#[utoipa::path]: operation id, tag, summary, description, the 2xx response, every specific problem response with content typeapplication/problem+json, and thedefaultresponse. When it is false, write no annotation. - Register the handler in the context's router. Unit-test it with the fake command and query buses of the repository (
FakeCommandBus,FakeQueryBus) and add one end-to-end scenario per outcome (success and each problem response).
GraphQL section
When framework.graphql is false, skip this section and record SKIPPED: framework.graphql is false. When it is true:
- Add the field to the context's query or mutation root. It calls the same command or query as the REST handler and converts a
Probleminto a GraphQL error with the shared conversion, so both interfaces report the same problem. - A context that has no GraphQL roots yet adds them to the schema's root tuples and its state to the schema data in the composition root.
- Regenerate the GraphQL snapshot with the target mapped by
make.generate_graphql_spec(see the snapshot co-change).
Infrastructure and wiring
When
persistence.engineis non-null, implement the repository port in the infrastructure crate with compile-time checked queries, and put its integration tests in<crate>/tests/integration/main.rs. A schema change goes through database-migrations in the same change.In the composition root named by
architecture.composition_root: register each new command and query handler, each subscriber, each adapter, the context's router and its GraphQL roots, and extend the wiring test. The places are listed by the repository skill; in the template they are:crates/service/src/bootstrap.rs register_commands, register_queries, event_bus, Adapters::connect crates/service/src/openapi.rs api_router nests the context router under /api crates/service/src/graphql/schema.rs Query and Mutation root tuples crates/service/src/bootstrap/tests.rs wiring testUnit tests live in a sibling
tests.rsnext to the module they test and use fake ports and fixed seeds; time and identifiers come from fakeClockandUuidGeneratorimplementations.
Snapshot co-change
- When
framework.openapiis true, run the target mapped bymake.generate_openapi_spec; whenframework.graphqlis true, run the target mapped bymake.generate_graphql_spec. Stage every regenerated snapshot file in the same change as the code. A snapshot is never edited by hand. - A key set to null records
not run (capability absent)and the degrade note "contract snapshot not regenerated"; the change then needs api-contract-development before review. - Continue with api-contract-development for snapshot validation, the Spectral bar and the breaking-change policy.
Evidence and the bounded loop
- Run the target mapped by
make.tests_with_coverage, then the target mapped bymake.e2e_tests, as the verification-workflow skill prescribes (in the background, log undertarget/rust-sdlc/logs/, polled until it exits, container route when the profile asks for it). - Record each target as
passed,failedornot run (<reason>)with a reason from the closed set:capability absent,no Docker,ask rule,no toolchain,skipped by triage,not changed,deferred to PR CI. - A failed target starts one iteration: read its log, fix the root cause in the code or the test, re-run that target, then re-run both evidence targets. The iterations count against the invoking stage's guard,
MAX_ITERATIONS=5, and the counter is never reset; used directly, the same cap of five applies. - A target that cannot run is not an iteration:
not run (no Docker)ornot run (no toolchain)ends the skillESCALATEDat once and is never fed to the fix loop. A fifth failed iteration endsESCALATEDwith the escalation block.
Constraints
- Never extract with the bare axum
Path,QueryorJsonin a handler; useApiPath,ValidatedQuery,ValidatedJsonorApiJson. - Never return data from a command, and never dispatch a command from a query or a subscriber.
- Never call
SystemTime::now,Instant::noworUuid::new_v4outside the adapters behindClockandUuidGenerator; never read I/O from a domain crate. - Never edit a contract snapshot by hand, and never leave a contract change without its regenerated snapshot.
- Never use
unwrap,expect,panic!, indexing orascasts in production code; never add amod.rsor a type namedError. - Never add
#[allow(...)],#[coverage(off)]or#[mutants::skip], and never lower a coverage floor or delete a test so that a target passes; fix the root cause. - Never edit a protected file (the list printed by
cargo xtask config-guard --list); a change that needs one stops with the escalation block andrecommended_action: approved-config-change label and a session restarted with ALLOW_PROTECTED_CONFIG_EDIT=1. - Write values only by profile key; concrete service values appear only in fences marked
# profile-example.
Verification
Self-checks on the change before the evidence targets, where <merge-base> is the merge base that the invoking stage computed (used directly: the output of git merge-base HEAD origin/<default branch>):
git diff --name-only <merge-base> -- '*.rs'
git diff <merge-base> -- '*.rs' | grep -nE '^\+.*(SystemTime::now|Instant::now|Uuid::new_v4)'
git diff <merge-base> -- '*.rs' | grep -nE '^\+[[:space:]]*(Path|Query|Json)\([^)]*\)[[:space:]]*:[[:space:]]*(Path|Query|Json)<'
The first command lists the changed files. The second must print nothing outside the adapters that implement Clock and UuidGenerator, and the third (a handler parameter destructured from a bare axum extractor) must print nothing; a hit is fixed before the evidence targets run.
Evidence block, printed once at the end:
skill: api-resource-development
source: repo+plugin | plugin
precedence: <repository rule followed instead of a step of this skill | none>
context: <group>/<context>
change: <REST method and path | GraphQL root.field | command <Name> | query <Name> | subscriber <Name>>
snapshots: <regenerated snapshot files | SKIPPED: <reason>>
targets run:
- <target>: passed | failed | not run (<reason>)
degrade notes: <one per line | none>
iteration: <n>/5
api-resource-development: SUCCESS | SUCCESS-WITH-REPORT | ESCALATED
The verdict is SUCCESS when every applicable target passed and no degrade note exists, SUCCESS-WITH-REPORT when the only notes are absent capabilities (not run (capability absent) or a SKIPPED: line for a false or null key), and ESCALATED otherwise. A resolved example:
- generate-openapi-spec: passed
- generate-graphql-spec: passed
- tests-with-coverage: passed
- e2e-tests: passed
api-resource-development: SUCCESS
When the verdict is ESCALATED, print the canonical block with the invoking stage's id and exit string:
=== SDLC ESCALATION ===
stage: <stage-id of the invoking command>
iteration: <n>/5
exit_condition: <exit string of the invoking stage, verbatim>
status: NOT MET
blocking_finding: <file:line | target + exit code | key that is null>
iteration_log: <one line per iteration: "<n>: <what ran> -> <result>">
recommended_action: <the human action>
=== END ===