https://github.com/tiago-marques/x-openapi-flow
OpenAPI describes APIs. _________ x-openapi-flow describes how they actually work: for developers and AI.
https://github.com/tiago-marques/x-openapi-flow
cli lifecycle oas openapi validation workflow
Last synced: about 19 hours ago
JSON representation
OpenAPI describes APIs. _________ x-openapi-flow describes how they actually work: for developers and AI.
- Host: GitHub
- URL: https://github.com/tiago-marques/x-openapi-flow
- Owner: tiago-marques
- License: mit
- Created: 2026-02-24T18:56:51.000Z (about 1 month ago)
- Default Branch: main
- Last Pushed: 2026-03-18T21:52:53.000Z (16 days ago)
- Last Synced: 2026-03-28T02:34:24.231Z (7 days ago)
- Topics: cli, lifecycle, oas, openapi, validation, workflow
- Language: JavaScript
- Homepage: https://tiago-marques.github.io/x-openapi-flow/
- Size: 4.51 MB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# OpenAPI describes APIs. x-openapi-flow turns them into executable workflows β for developers and AI agents.
## Define your API workflows in openapi.x.json and execute them without writing custom clients or orchestration logic

[](https://www.npmjs.com/package/x-openapi-flow)
[](https://www.npmjs.com/package/x-openapi-flow)



[](https://github.com/tiago-marques/x-openapi-flow/actions/workflows/x-openapi-flow-validate.yml)
[](https://github.com/tiago-marques/x-openapi-flow/issues)
[](https://github.com/tiago-marques/x-openapi-flow/commits/main)

> π 2,100+ downloads in the first 3 weeks!
## β‘ Get started in seconds
```
npx x-openapi-flow init --suggest-transitions
```
### This generates an openapi.x.json file where you can declaratively define how your API should be executed β not just described.
> See your API lifecycle come alive from your OpenAPI spec, with one simple command
> Validate, document, and generate flow-aware SDKs automatically.

## What is this?
### x-openapi-flow extends your OpenAPI specification with a workflow layer.
> openapi.json β describes your API
> openapi.x.json β describes how to use it (flows)
### Instead of writing imperative code to orchestrate API calls, you define workflows declaratively and run them anywhere.
`x-openapi-flow` adds a **declarative state machine** to your OpenAPI spec.
Model resource lifecycles, enforce valid transitions, and generate flow-aware artifacts for documentation, SDKs, and automation.
## π Example
> Define stateful workflows and lifecycle transitions directly inside your OpenAPI operations:
```json
{
"operationId": "createOrder",
"x-openapi-flow": {
"version": "1.0",
"id": "create-order",
"current_state": "created",
"description": "Creates an order and starts the lifecycle",
"transitions": [
{
"transition_id": "order-created-to-paid",
"trigger_type": "synchronous",
"condition": "Payment is confirmed",
"decision_rule": "payOrder:response.200.body.payment_status == 'approved'",
"target_state": "paid",
"next_operation_id": "payOrder",
"operation_role": "mutate",
"prerequisite_operation_ids": ["createOrder"],
"evidence_refs": [
"payOrder:response.200.body.payment_status"
],
"propagated_field_refs": [
"createOrder:response.201.body.order_id"
],
"failure_paths": [
{
"reason": "Payment denied",
"target_state": "payment_failed",
"next_operation_id": "getOrder"
}
]
}
]
}
}
```
This flow defines an order lifecycle directly inside your OpenAPI:
* Starts in the `created` state
* Transitions to `paid` when payment is confirmed
* Supports both synchronous and polling-based transitions
* Propagates data between operations automatically
* Can include explicit decision/evidence and failure-path metadata for AI-guided orchestration
Instead of manually orchestrating API calls, the workflow is fully described alongside your API specification.
## Why This Exists
Building APIs is cheap. Building **complex, multi-step APIs that teams actually use correctly** is hard.
Teams face recurring problems:
- π **Manual documentation is brittle** β OpenAPI specs are static, often out of sync with real workflows
- π€ **AI agents can hallucinate** β LLMs and code-generating agents may produce invalid calls if workflows are unclear or undocumented
- π€― **Workflows are confusing** β multi-step operations are hard to track for humans and AI agents
- β οΈ **Invalid calls slip through** β developers make mistakes because lifecycle rules arenβt enforced
- β±οΈ **Integration slows down** β SDKs, Postman collections, and docs need constant manual updates
- π‘οΈ **Hard to prevent errors in production** β without explicit lifecycle rules, invalid operations can reach live systems, causing outages or inconsistencies
x-openapi-flow exists to **solve these pains**: it makes lifecycles explicit, validates transitions automatically, and generates flow-aware docs and SDKs β **so teams move faster, make fewer mistakes, and ship confident integrations**.
## What This Enables
Turn your OpenAPI spec into a single source of truth for API behavior:
- Visualize API lifecycles directly in [Swagger UI](#swagger-ui-demo) and [Redoc](#redoc-demo)
- Validate flows and state transitions in [CI pipelines](#cli-commands)
- Generate [lifecycle diagrams automatically](#mermaid-example) from your OpenAPI spec
- Build [SDKs](#sdk-generation) that understand and respect API workflows
- Export [Postman](#postman-demo) and [Insomnia](#insomnia-demo) collections organized by lifecycle
- Create [AI-ready API contracts](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/engineering/AI-Sidecar-Authoring.md) for agentic integrations
## Quick Start (without OpenAPI file)
Fastest way to see value (guided scaffold):
```bash
npx x-openapi-flow quickstart
cd x-openapi-flow-quickstart
npm install
npm start
```
Optional runtime:
```bash
npx x-openapi-flow quickstart --runtime fastify
```
Then run:
```bash
curl -s -X POST http://localhost:3110/orders
curl -i -X POST http://localhost:3110/orders//ship
```
Expected: `409 INVALID_STATE_TRANSITION`.
---
### If you already have an OpenAPI file, use the sidecar workflow:
Initialize flow support in your project:
```bash
npx x-openapi-flow init
# optional: infer suggested transitions using naming heuristics
npx x-openapi-flow init --suggest-transitions
```
After regenerating your OpenAPI file, apply and validate the flow (optional):
```bash
npx x-openapi-flow apply openapi.yaml --out openapi.flow.yaml
npx x-openapi-flow validate openapi.flow.yaml --profile strict --strict-quality
```
This will:
- enrich your OpenAPI spec with flow metadata
- validate lifecycle consistency
- catch invalid transitions early
π‘ Tip: run this in CI to enforce API workflow correctness
### Less Verbose DSL for Large Flows
For larger APIs, you can define flow rules by resource (with shared transitions/defaults) and reduce duplication in sidecar files.
See: [Sidecar Contract](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/reference/Sidecar-Contract.md)
### GitHub Action (One-Step CI Validation)
Use the official reusable action to validate lifecycle rules in CI with a single step:
```yaml
- name: Validate OpenAPI flow rules
uses: tiago-marques/x-openapi-flow/.github/actions/validate@main
with:
openapi-file: openapi.flow.yaml
profile: strict
strict-quality: "true"
```
Integration guide: [GitHub-Actions-Integration.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/integrations/GitHub-Actions-Integration.md)
Hereβs a real-world payment lifecycle represented in x-openapi-flow:
```
CREATED -> AUTHORIZED -> CAPTURED -> REFUNDED
```
Generate a visual graph of the lifecycle:
```bash
npx x-openapi-flow graph openapi.flow.yaml --format mermaid
```
Resulting diagram:
```mermaid
graph TD
CREATED --> AUTHORIZED
AUTHORIZED --> CAPTURED
CAPTURED --> REFUNDED
```
> This visualization makes your API workflow explicit, easy to communicate, and ready for documentation or demos.
Create a TypeScript SDK that **respects your APIβs lifecycle and transition rules**, following best practices seen in leading companies like **Stripe** and **Adyen**:
- **Orchestrator by model**: each resource exposes methods that enforce valid transitions
- **Chainable API calls**: perform sequences naturally and safely
```bash
npx x-openapi-flow generate-sdk openapi.flow.yaml --lang typescript --output ./sdk
```
Example usage:
```ts
const payment = await sdk.payments.create({ amount: 1000 });
await payment.authorize();
await payment.capture();
```
> This SDK guides developers through valid transition paths, following patterns used by market leaders to ensure safe and intuitive integrations.
## Runtime Enforcement (Express + Fastify)
CI validation is important, but production safety needs request-time enforcement.
`x-openapi-flow` now includes an official runtime guard for Node.js that can block invalid state transitions during request handling.
- Works with **Express** and **Fastify**
- Resolves operations by `operationId` (when available) or by method + route
- Reads current resource state using your own persistence callback
- Blocks invalid transitions with explicit `409` error payloads
Install and use directly in your API server:
```js
const {
createExpressFlowGuard,
createFastifyFlowGuard,
} = require("x-openapi-flow/lib/runtime-guard");
```
Express example:
```js
const express = require("express");
const { createExpressFlowGuard } = require("x-openapi-flow/lib/runtime-guard");
const openapi = require("./openapi.flow.json");
const app = express();
app.use(
createExpressFlowGuard({
openapi,
async getCurrentState({ resourceId }) {
if (!resourceId) return null;
return paymentStore.getState(resourceId); // your DB/service lookup
},
resolveResourceId: ({ params }) => params.id || null,
})
);
```
Fastify example:
```js
const fastify = require("fastify")();
const { createFastifyFlowGuard } = require("x-openapi-flow/lib/runtime-guard");
const openapi = require("./openapi.flow.json");
fastify.addHook(
"preHandler",
createFastifyFlowGuard({
openapi,
async getCurrentState({ resourceId }) {
if (!resourceId) return null;
return paymentStore.getState(resourceId);
},
resolveResourceId: ({ params }) => params.id || null,
})
);
```
Error payload for blocked transition:
```json
{
"error": {
"code": "INVALID_STATE_TRANSITION",
"message": "Blocked invalid transition for operation 'capturePayment'. Current state 'CREATED' cannot transition to this operation.",
"operation_id": "capturePayment",
"current_state": "CREATED",
"allowed_from_states": ["AUTHORIZED"],
"resource_id": "pay_123"
}
}
```
More details: [Runtime Guard](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/reference/Runtime-Guard.md)
### 5-Minute Demo: Real Runtime Block (E-commerce Orders)
Want to see the value immediately? Use the official minimal demo:
- [example/runtime-guard/minimal-order/README.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/example/runtime-guard/minimal-order/README.md)
Run in under 5 minutes:
```bash
cd example/runtime-guard/minimal-order
npm install
npm start
```
Create an order, then try to ship before payment (must return `409 INVALID_STATE_TRANSITION`):
```bash
curl -s -X POST http://localhost:3110/orders
curl -i -X POST http://localhost:3110/orders//ship
```
HTTPie equivalent:
```bash
http POST :3110/orders
http -v POST :3110/orders//ship
```
## Programmatic State Machine Engine
Use a reusable deterministic engine independently of CLI and OpenAPI parsing:
```js
const { createStateMachineEngine } = require("x-openapi-flow/lib/state-machine-engine");
const engine = createStateMachineEngine({
transitions: [
{ from: "CREATED", action: "confirm", to: "CONFIRMED" },
{ from: "CONFIRMED", action: "ship", to: "SHIPPED" },
],
});
engine.canTransition("CREATED", "confirm");
engine.getNextState("CREATED", "confirm");
engine.validateFlow({ startState: "CREATED", actions: ["confirm", "ship"] });
```
More details: [State Machine Engine](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/reference/State-Machine-Engine.md)
### OpenAPI to Engine Adapter
Convert `x-openapi-flow` metadata to a pure engine definition:
```js
const { createStateMachineAdapterModel } = require("x-openapi-flow/lib/openapi-state-machine-adapter");
const { createStateMachineEngine } = require("x-openapi-flow/lib/state-machine-engine");
const model = createStateMachineAdapterModel({ openapiPath: "./openapi.flow.yaml" });
const engine = createStateMachineEngine(model.definition);
```
More details: [OpenAPI State Machine Adapter](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/reference/OpenAPI-State-Machine-Adapter.md)
## Who Benefits Most
x-openapi-flow is ideal for teams and organizations that want **clear, enforceable API workflows**:
- **API-first organizations** β maintain a single source of truth for API behavior
- **Teams building AI agents** β provide AI-friendly contracts and enforce correct API usage, so agents can safely call endpoints in the right order without guessing or violating workflow rules
- **API platform teams** β ensure consistent lifecycle rules across endpoints
- **Companies with complex API workflows** β reduce errors and ambiguity in multi-step processes
- **SDK teams** β generate flow-aware SDKs that guide developers
## Why x-openapi-flow?
See how **x-openapi-flow extends OpenAPI** to make your API workflows explicit, enforceable, and actionable:
| Capability | OpenAPI | x-openapi-flow |
| --- | --- | --- |
| Endpoint contracts | β
Yes | β
Yes (fully compatible, extended) |
| Lifecycle states | β No | β
Yes β define states for each resource |
| Transition validation | β No | β
Yes β catch invalid calls before runtime |
| Flow diagrams | β No | β
Yes β generate visual lifecycle graphs |
| Usage guidance (next valid actions) | Limited/manual | β
Built-in via lifecycle metadata β guides developers and AI agents |
## Integration Demos
Explore how x-openapi-flow integrates with popular API tools, making lifecycles and flows explicit for documentation and testing.
### Swagger UI β Visualize Flows in Your Docs
```bash
cd example/swagger-ui
npm install
npm run apply
npm start
```

> Lifecycle panel shows valid states and transitions

> Detailed view of transitions per operation
### Redoc β Flow-Aware Documentation
```bash
cd example/redoc
npm install
npm run apply
npm run generate
```



> Auto-generated lifecycle diagrams make documentation clear and consistent
### Postman β Organized API Collections
```bash
cd example/postman
npm install
npm run apply
npm run generate
```


> Collections reflect lifecycle order, reducing integration errors
### Insomnia β Organized API Collections
```bash
cd example/insomnia
npm install
npm run apply
npm run generate
```


> Requests are pre-organized according to lifecycle transitions
## CLI Reference β Common Commands
Use x-openapi-flow from the command line to **manage, validate, visualize, and generate SDKs/docs for your API workflows**.
### General
```bash
npx x-openapi-flow help [command] # show help for a specific command
npx x-openapi-flow --help # general help
npx x-openapi-flow version # show version
npx x-openapi-flow doctor [--config path] # check setup and config
npx x-openapi-flow completion [bash|zsh] # enable shell autocompletion
npx x-openapi-flow quickstart [--dir path] [--runtime express|fastify] [--force] # scaffold runnable onboarding project
```
### Workflow Management
```bash
# initialize flow support
npx x-openapi-flow init [--flows path] [--force] [--dry-run]
# apply flows to OpenAPI
npx x-openapi-flow apply [openapi-file] [--flows path] [--out path]
# validate transitions
npx x-openapi-flow validate [--profile core|relaxed|strict] [--strict-quality] [--semantic]
```
### Visualization & Documentation
```bash
# generate lifecycle diagrams
npx x-openapi-flow graph [openapi-file] [--format mermaid|json]
# generate Redoc docs
npx x-openapi-flow generate-redoc [openapi-file] [--output path]
# export flows
npx x-openapi-flow export-doc-flows [openapi-file] [--output path] [--format markdown|json]
```
### SDK Generation
```bash
# generate flow-aware SDK
npx x-openapi-flow generate-sdk [openapi-file] --lang typescript [--output path]
```
### Test Generation
```bash
# generate executable flow tests (happy path + invalid transitions)
npx x-openapi-flow generate-flow-tests [openapi-file] [--format jest|vitest|postman] [--output path]
# postman/newman-oriented collection with flow scripts
npx x-openapi-flow generate-flow-tests [openapi-file] --format postman [--output path] [--with-scripts]
```
Full details:
- [CLI-Reference.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/reference/CLI-Reference.md)
- [README.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/x-openapi-flow/README.md)
## Documentation and Guides
Get the most out of x-openapi-flow with detailed guides, examples, and integration instructions:
- **Adoption Guide** β [docs/wiki/getting-started/Adoption-Playbook.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/getting-started/Adoption-Playbook.md)
Learn how to introduce x-openapi-flow into your API workflow efficiently
- **Troubleshooting** β [docs/wiki/reference/Troubleshooting.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/reference/Troubleshooting.md)
Quick solutions to common issues and validation errors
- **Real Examples** β [docs/wiki/engineering/Real-Examples.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/engineering/Real-Examples.md)
Explore real OpenAPI specs enhanced with lifecycle metadata
- **Integrations**:
- **GitHub Actions** β [docs/wiki/integrations/GitHub-Actions-Integration.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/integrations/GitHub-Actions-Integration.md)
Validate flow rules in CI in one reusable workflow step
- **Swagger UI** β [docs/wiki/integrations/Swagger-UI-Integration.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/integrations/Swagger-UI-Integration.md)
See flow-aware panels in Swagger UI
- **Redoc** β [docs/wiki/integrations/Redoc-Integration.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/integrations/Redoc-Integration.md)
Generate lifecycle diagrams in Redoc documentation
- **Postman** β [docs/wiki/integrations/Postman-Integration.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/integrations/Postman-Integration.md)
Organize collections according to valid transitions
- **Insomnia** β [docs/wiki/integrations/Insomnia-Integration.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/docs/wiki/integrations/Insomnia-Integration.md)
Pre-configure requests according to lifecycle flows
## Roadmap
Weβre actively expanding x-openapi-flow to support multiple platforms and SDKs. Check our progress:
- π **Roadmap Overview** β [#2](https://github.com/tiago-marques/x-openapi-flow/issues/2)
See planned features and high-level goals
- π **Python SDK MVP** β [#3](https://github.com/tiago-marques/x-openapi-flow/issues/3)
Enable Python developers to use flow-aware SDKs
- π **Go SDK MVP** β [#4](https://github.com/tiago-marques/x-openapi-flow/issues/4)
Bring lifecycle-aware SDKs to Go projects
- β **Kotlin SDK MVP** β [#5](https://github.com/tiago-marques/x-openapi-flow/issues/5)
Support Android and JVM developers with flow-aware SDKs
## Changelog
Keep track of updates and improvements in x-openapi-flow:
- **Latest Version (v1.7.0)** β [CHANGELOG.md#170---2026-04-02](https://github.com/tiago-marques/x-openapi-flow/blob/main/CHANGELOG.md#170---2026-04-02)
See what shipped in the current release
- **Version History** β [CHANGELOG.md](https://github.com/tiago-marques/x-openapi-flow/blob/main/CHANGELOG.md)
Review the full version history and past updates
- **Release Notes** β [GitHub Release v1.7.0](https://github.com/tiago-marques/x-openapi-flow/releases/tag/v1.7.0)
See detailed notes for the latest release, including new features and fixes
## Documentation Language Policy
To ensure clarity and accessibility for the global developer community, **all project documentation should be written in English**. This helps contributors, users, and AI agents understand and use x-openapi-flow consistently.