Documentation

1 つの YAML から信頼できるモック API を作る。

specter はフロントエンド開発、デモ、自動テスト、API 契約の確認に使える軽量なモック API サーバーです。config.yml にルートを書き、単一バイナリを起動するだけで、アプリを作り直さずに挙動を調整できます。

config.yml
cors: true

routes:
  - path: /users
    method: GET
    status: 200
    response:
      - id: 1
        name: Alice

  - path: /users/:id
    method: GET
    response:
      id: ":id"
      name: Alice

Quick Start

空のフォルダからモック API へ

01

スターターを作成

specter init

現在のディレクトリに config.yml を作成します。

02

サーバーを起動

specter -c config.yml

API は 8080、コントロール UI は 4444 で起動します。

03

ルートを呼び出す

curl http://localhost:8080/users

YAML を編集して保存すると、specter が自動で再読み込みします。

config.yml

完全リファレンス

config は 1 つのルートだけの小さなファイルにも、状態管理、条件分岐、fixtures、OpenAPI 検証、proxy、stores、callbacks、delays、streams を含む本格的なシナリオにもできます。

トップレベルのフィールド

YAML ファイルのルートに 1 回だけ書くフィールドです。

FieldTypeDescription
corsbooleanCORS headers を有効化し、OPTIONS preflight requests を処理します。
proxystring一致する route がない requests を実 backend に転送します。
openapistringrequest / response validation に使う OpenAPI YAML または JSON file の path です。
openapi_strictbooleantrue の場合、invalid requests は warning header の追加だけでなく 400 を返します。
openapi_strict_responsebooleantrue の場合、invalid mock responses は warning header 付きで返されず 500 になります。
includelist他の YAML files から routes を merge します。glob patterns も使えます。
routeslistspecter が提供する route definitions です。

ルートのフィールド

routes の各要素は、モック、proxy、store 操作、redirect、stream のいずれかを表します。

FieldTypeDescription
pathstring必須。URL path です。:param 形式の path parameters を使えます。
methodstring必須。GET、POST、PUT、PATCH、DELETE などの HTTP method です。
statusintresponse status code です。default は 200 です。
responseanyinline の JSON object、array、scalar、string response body です。
headersmaproute に付与する custom response headers です。
content_typestringresponse MIME type です。default は application/json です。
delayint固定 response delay を milliseconds で指定します。
delay_minintrandom delay の最小値を milliseconds で指定します。delay_max と一緒に使います。
delay_maxintrandom delay の最大値を milliseconds で指定します。delay_min と一緒に使います。
error_ratefloatinjected error を返す確率を 0.0 から 1.0 で指定します。
error_statusintinjected errors の status code です。default は 503 です。
on_callint1 始まりの指定 call number のときだけこの route に match します。
matchlistquery、headers、body、form data、cookies、GraphQL に基づく conditional responses です。
modestringresponses の選択方法です。sequential または random を使います。
responseslistcycling、retry simulation、random behavior 用の複数 response entries です。
rate_limitint429 を返すまでの最大 requests 数です。
rate_resetintrate-limit counter が reset されるまでの秒数です。429 に Retry-After を追加します。
statestringserver state がこの値と等しいときだけ match します。
set_statestringresponse 後に server state を設定します。
varsmap指定した variables がすべてこの値と等しいときだけ match します。
set_varsmapresponse 後に named variables を設定します。値には templates を使えます。
webhookobjectresponse 後に outgoing callback を送信します。
filestringJSON、YAML、text fixture file から response body を返します。
scriptstringresponse body を生成する Go template です。file と response より優先されます。
proxystringこの route を実 backend に転送します。mock response fields より優先されます。
store_pushstringrequest body を in-memory store に追加し 201 を返します。
store_liststringin-memory store の items を filtering、sorting、pagination 付きで一覧します。
store_getstringstore_key path parameter で store item を 1 件取得します。
store_putstringstore item を replace または upsert します。
store_patchstringrequest body を store item に merge します。
store_deletestringstore item を 1 件削除します。
store_clearstringnamed store 内のすべての item を削除します。
store_keystringitem ID として使う path parameter です。default は id です。
streambooleanServer-Sent Events stream として response します。
eventsliststream route 用の順序付き SSE events です。
stream_repeatbooleanclient が disconnect するまで SSE events を繰り返します。
set_cookieslistresponse に cookies を設定します。
redirectstring別の path または URL に redirect します。
redirect_statusintredirect status code です。301、302、303、307、308 を使います。

match のフィールド

同じ method と path で、リクエスト内容に応じてレスポンスを分岐したいときに使います。1 つの match 内の条件はすべて満たす必要があります。

FieldTypeDescription
querymapquery parameters を Go regular expressions で match します。
headersmaprequest headers を match します。header names は case-insensitive です。
bodymaptop-level JSON request body fields を match します。
body_pathmapuser.role のような dot notation で nested JSON fields を match します。
formmapapplication/x-www-form-urlencoded request bodies を match します。
graphqlobjectGraphQL operationName と variables を match します。
cookiesmaprequest cookies を regex patterns で match します。
statusintこの match が発火したときに返す status code です。
responseanyこの match が発火したときに返す response body です。
response_headersmapこの match にだけ適用する headers です。route headers を override します。
content_typestringこの match にだけ適用する content type です。
delayintこの match 用の追加 delay です。route delay の後に加算されます。
set_statestringこの match が発火したときだけ適用する state transition です。
set_varsmapこの match が発火したときだけ適用する variable updates です。
filestringこの match が発火したときだけ返す fixture file です。
scriptstringこの match が発火したときだけ返す template response です。

responses の要素

responses と mode: sequential / random を使うと、retry、polling、不安定な API、変化するデータを再現できます。

FieldTypeDescription
on_callintこの response entry を特定の call number に固定します。
statusintこの response entry の status です。
responseanyこの response entry の inline body です。
content_typestringこの response entry の content type です。
delayintこの response entry の delay です。
filestringこの response entry の fixture file です。
scriptstringこの response entry の template body です。

Examples

Examples gallery

よくある mock pattern ごとに、すぐ生成できるサンプル config と使いどころをまとめました。CLI では specter examples <name> で作成できます。

詳しい gallery を読む
auth

login、protected endpoint、state、vars、401 response の流れを試せます。

specter examples auth
crud

in-memory store に REST endpoint を接続し、一覧・詳細・作成・更新・削除を再現します。

specter examples crud
pagination

filtering、sorting、limit、offset を使う list endpoint の starting point です。

specter examples pagination
graphql

operationName と variables に応じて /graphql の response を分岐します。

specter examples graphql
webhooks

response 後の asynchronous callback を local listener に送信します。

specter examples webhooks
sse

Server-Sent Events の stream と繰り返し event を再現します。

specter examples sse
openapi

OpenAPI spec による request / response validation を試せます。

specter examples openapi
polling

long-running job の queued / running / complete を sequential responses で表現します。

doc/examples.md
errors

rate limit、flaky 503、latency、400/404 response で error UI を鍛えます。

specter examples errors

Comparison

どの mock-server tool を選ぶか

Specter は YAML-first の local mock server です。json-server、Prism、WireMock と重なる部分はありますが、state、stores、scenarios、timelines、request assertions、Web UI を 1 つの local workflow にまとめることを重視しています。

比較ガイドを読む
json-server

JSON database から CRUD REST API をすばやく作る用途に向いています。Specter は同じ path で条件分岐・state・scenario・assertion が必要なときに向いています。

Prism

OpenAPI / Postman contract を source of truth にした mock と validation proxy に強い tool です。Specter は OpenAPI validation に加えて hand-written behavior を重ねたいときに向いています。

WireMock

rich matching、verification、record/playback、JVM integration、service virtualization に強い mature tool です。Specter は小さく読める YAML と built-in UI で local dev / E2E を軽く回したいときに向いています。

Recipes

よく使う config パターン

条件付きレスポンス

request body、query、headers、cookies、form data、GraphQL の値で分岐できます。

config.yml
routes:
  - path: /users
    method: POST
    match:
      - body:
          role: admin
        status: 201
        response:
          id: 1
          role: admin
      - query:
          preview: "^true$"
        response_headers:
          X-Preview: "true"
        response:
          id: 2
          preview: true
    status: 400
    response:
      error: no matching scenario

状態を持つフロー

login flow やシナリオの分岐には state、set_state、vars、set_vars を使います。

config.yml
routes:
  - path: /login
    method: POST
    set_state: logged_in
    set_vars:
      role: "{{ .body.role }}"
    response:
      token: abc123

  - path: /profile
    method: GET
    state: logged_in
    vars:
      role: admin
    response:
      name: Alice
      role: admin

  - path: /profile
    method: GET
    status: 401
    response:
      error: unauthorized

インメモリ CRUD

REST endpoint を名前付き store に直接接続できます。store のデータはサーバー再起動時にリセットされます。

config.yml
routes:
  - path: /users
    method: POST
    store_push: users

  - path: /users
    method: GET
    store_list: users

  - path: /users/:id
    method: PATCH
    store_patch: users
    store_key: id

  - path: /users/:id
    method: DELETE
    store_delete: users
request
GET /users?role=admin&_sort=name&_order=asc&_limit=10&_offset=0

OpenAPI、proxy、chaos、SSE

実サービスと mock を混ぜ、request 検証、jitter、failure injection、event stream を使えます。

config.yml
include:
  - routes/*.yml

openapi: ./openapi.yaml
openapi_strict: true
openapi_strict_response: false
proxy: https://api.example.com

routes:
  - path: /flaky
    method: GET
    delay_min: 150
    delay_max: 900
    error_rate: 0.25
    error_status: 503
    response:
      ok: true

  - path: /events
    method: GET
    stream: true
    events:
      - data: { type: connected }
      - event: done
        data: { ok: true }
        delay: 500

Templates と faker

template は .body、.query、.params、.headers、.method、.path を参照できます。

config.yml
routes:
  - path: /greet
    method: POST
    script: |
      {
        "message": "Hello, {{ .body.name | default "friend" }}",
        "id": "{{ fake "uuid" }}",
        "created_at": "{{ now }}"
      }
namefirst_namelast_nameemailuuidphoneurlipusernamepasswordwordsentenceparagraphcolorcountrycityzipstreetcompanyjobintfloatbooldatedatetime

Fixtures、redirects、cookies、webhooks

大きな JSON/YAML/text fixture には file、HTTP redirect には redirect、認証 simulation には set_cookies、非同期 callback には webhook を使います。

config.yml
routes:
  - path: /login
    method: POST
    set_cookies:
      - name: session
        value: sess_abc123
        http_only: true
    webhook:
      url: http://localhost:9000/events
      body: { event: logged_in }
    response: { ok: true }

  - path: /old
    method: GET
    redirect: /new
    redirect_status: 301

CLI

よく使うコマンド

flags は environment variables より優先されます。API のデフォルト port は 8080、組み込み dashboard は 4444 です。無効化するには --ui-port 0 を指定します。

commands
specter init
specter validate -c config.yml
specter -c config.yml -p 8080
specter gen -i openapi.yml -o config.yml
specter record -t http://api.example.com -o config.yml

Contributing

specter を一緒に良くする

docs、examples、bug fixes、CLI behavior、validation、UI improvements、新しい mock-server features への contribution を歓迎します。変更は focused にし、挙動変更には tests を追加し、config や CLI behavior が変わる場合は docs も更新してください。

1. Fork and branch

目的が分かる branch を作り、小さく意味のある変更にします。

2. Validate locally

関連する tests を実行し、docs examples には specter validate -c config.yml を使います。

3. Open a pull request

scenario、変更内容、既存 config への compatibility notes を書いて pull request を作成します。