Skip to content

9. API functional tests: API Functional QA

Contract checks tell you an API still has the right shape. They don't tell you whether placing an order charges the right amount, whether cancelling really keeps the row marked as cancelled, or whether a malformed request crashes the server. k11 API Functional QA writes and runs those tests, down to the database row.

It is also the foundation for three other tools. API Security QA, Integration QA and Performance QA all read its settings file, .qa-mcp/api-test.yaml, and Integration and Performance QA build on its flows.

Configure: .qa-mcp/api-test.yaml

spec: openapi.yaml
default_environment: local
environments:
  local:   { base_url: http://localhost:8080 }
  staging: { base_url: https://staging.example.com, allow_writes: true }
  prod:    { base_url: https://api.example.com }        # read-only: writes refused
auth:
  default: { type: bearer, token: "${ENV:API_TOKEN}" }
  # basic: {username, password} · api_key: {header, value} · oauth2: {token_url, client_id, client_secret, scope}
databases:
  main: { url: "${ENV:TEST_DB_URL}", allow_writes: true, mask: [email, card_number] }
fixtures:
  customer:
    db: main
    insert: { table: customers, values: { id: "${uuid}", email: "${random_email}", name: Test Customer } }
    delete: { table: customers, where: { id: "${id}" } }
Section What it holds
environments Base URLs, which may change data (see guardrails below), and an optional default auth profile per environment
auth Named profiles: bearer, basic, api_key or oauth2 (client credentials); secrets as ${ENV:NAME}
databases Test databases: SQLite (built in), PostgreSQL ([postgres]), MySQL/MariaDB ([mysql]) or SQL Server ([mssql]); columns to mask in reports
fixtures Test data inserted before a flow and deleted after it, in the database or through an API call

A flow

Flows are YAML files in tests/api/:

name: Customer cancels an order and it is soft-deleted
fixtures: [customer]                       # seeded in the test database, removed afterwards
steps:
  - name: place an order
    call: POST /orders
    body: { customerId: "${fixture.customer.id}", channel: web, items: [{ sku: HAT-2, qty: 1 }] }
    expect:
      status: 201
      json: { "$.status": pending, "$.total": 15.0, "$.items": { length: 1 } }
    save: { orderId: "$.id" }

  - name: cancel it
    call: DELETE /orders/${orderId}
    expect: { status: 204 }

  - name: the row is kept and marked deleted
    db: SELECT status, deleted_at FROM orders WHERE id = :orderId
    params: { orderId: "${orderId}" }
    expect: { rows: 1, row: { status: cancelled, deleted_at: { ne: null } } }

cleanup:
  - db: DELETE FROM orders WHERE id = :orderId
    params: { orderId: "${orderId}" }

Checks (expect):

  • HTTP: status (201, "2xx", [400, 422]), json paths ($.items[0].qty, $.items[*].sku, $.items.length), headers, body_contains, max_ms, and the response schema from the spec (on by default).
  • Database: rows, row (the first row) and rows_include.
  • Values match literally or with operators: eq ne gt gte lt lte approx contains matches length type in exists empty.

Variables: save from JSON paths, headers (header:Location) or status, and use them as ${orderId}. Generators: ${uuid}, ${random_email}, ${random_int}, ${now}, ${today}. Secrets: ${ENV:NAME}.

Failures: a step that only fails value checks lets the flow continue, to gather more evidence. A wrong status, a 5xx, a blocked write or a missing saved value stops it. continue_on_failure: true runs every step. Cleanup always runs.

Writing flows with the agent

/api-story-test (or /api-functional-qa:api-story-test) starts with review_user_story (Chapter 4), then draft_flow proposes scenarios, the spec operations involved and a skeleton. While writing, the agent can explore with call_api (one request, same guardrails) and query_db (one read-only query), then save with write_flow and run with run_flows.

Negative tests from the spec

/api-negative-tests POST /orders, or the generate_negative_tests tool, derives cases from the spec, including nested fields and array items: missing required fields, wrong types, values outside enums and min/max/length limits, no credentials, unknown IDs. Every case must get a 4xx, never a 5xx.

From the tool's demo: 18 cases for POST /orders, 16 correct, and two returned HTTP 500, one of them a crash nobody had planted:

  • ✗ wrong type for items[0].qty is rejected: got 500. A 5xx is a bug.
  • ✗ missing required field items[0].qty is rejected: got 500. A 5xx is a bug.

Where the database check earns its place

The same demo's order-total flow orders two bags at 42.50:

❌ Order total is quantity times price - place an order for two bags: failed. Response: HTTP 201. ✗ $.total 85.0: expected 85.0, got 42.5 - the database stores 85.00: passed - order history shows 85.00: passed

Without the database check this is "the total is wrong". With it, it's "the total is stored correctly and only the POST /orders response is wrong", which points straight at the code.

Guardrails

Risk What happens
Changing production data POST/PUT/PATCH/DELETE are refused on environments named like production (prod, production, live) unless they set both allow_writes: true and production_writes_acknowledged: true. Other environments must be local, named like a test environment, or set allow_writes: true
Writing to a database db steps only read, on a read-only connection inside a rolled-back transaction. Writes happen only in fixtures and cleanup, on databases with allow_writes: true
SQL injection Values go in :named parameters; ${...} inside SQL text is refused, as is more than one statement
Leaking secrets Credentials come from ${ENV:NAME} and are masked everywhere, as are database columns listed under mask
Sending credentials elsewhere Requests must stay on the environment's host
Runaway queries At most 1,000 rows per query, with timeouts on every connection and request

In CI

k11-api-functional-qa-mcp run --env staging --fail-on never
Option Default
[paths] everything in tests/api/
--env NAME default_environment
--tag TAG all flows (repeatable)
--report-dir PATH .qa-mcp/api-test-report
--fail-on LEVEL any: fail on failed, blocked or error; also failed or never

It writes api-test-report.md, api-test-report.json and api-test-junit.xml. To keep a flow without this tool, export_pytest turns it into plain pytest + httpx code.

Evidence for the gate

api-test-report.json is the api_tests kind, and the built-in policy requires it on every change.

Rule Outcome When
api.server_error block a 5xx in any step
api.flow_failed block a flow failed
api.flow_not_run needs a person flows were refused by guardrails or errored, so they proved nothing

Changes under api/, routes/, controllers/, handlers/, endpoints/, services/, migrations and SQL files require it too.