# Generate OpenAPI 3.1 Negative Tests From the Spec, Then Check Your Validator

> A 3.1 Orders API with two 3.0 spellings run through the OpenAPI Negative Test Generator: one stops Ajv compiling, one Ajv quietly honours. The 40 generated Playwright tests pass 40/40 on Ajv defaults and 36/40 on Fastify's options, and eight passes trip the wrong keyword.

- Author: [Shashank Rawlani](https://shashank.rawlani.com)

- Published: 2026-11-20T05:30:00.000Z

- Updated: 2026-11-20T05:30:00.000Z

- Category: Tools & Reviews

- Canonical source: https://automationtester.in/blog/tools-reviews/openapi-31-negative-tests-from-the-spec

- Tags: openapi, api-testing, negative-testing, json-schema, playwright

**Quick answer:** Paste the OpenAPI document into the [OpenAPI Negative Test Generator](https://automationtester.in/tools/openapi-negative-tests), fix every spec problem it reports before trusting a single case, then download the Playwright tests and run them against a server whose validator you know. On a sample Orders API, the same 40 generated tests passed 40/40 against Ajv with its default options and 36/40 against Ajv configured with Fastify's documented defaults, because type coercion and `removeAdditional` turned four invalid requests into valid ones. Eight of the 36 that did pass were rejected by a different keyword than the one the test was written for.

An OpenAPI 3.1 file says `unitPrice` has `minimum: 0` and `exclusiveMinimum: true`. The team reads it as "greater than zero", and a service that compiles it with Ajv in 2020-12 mode will not start: Ajv refuses the schema, with or without strict mode. Fix that, write a test that sends `"quantity": "1"` and expects 422, and on a service running Fastify's default validator settings it gets 201, because the string was converted to a number before validation ran.

The second problem is not in the spec at all, and a test runner that only checks status codes hides part of it even once you find it. This review runs one deliberately flawed 3.1 document through the generator and its output against two validator configurations. Choosing one mutation per rule and placing it on the boundary is covered in [designing negative API tests from the contract](https://automationtester.in/blog/automation-tutorials/design-negative-api-tests-from-contract); this article is about what happens when you automate that list.

## The job the generator does, and the jobs it does not

The tool reads an OpenAPI 3.0 or 3.1 document in the browser and lists, per operation, the requests the document says must fail: missing credentials, a missing required body, each required property left out, wrong types, nulls where null is not allowed, values one step past each bound, enum and pattern misses, malformed formats and undeclared properties. It writes that list as a Markdown checklist or as Playwright request tests with a control test per operation.

It never sends a request. It does not fuzz, it does not learn from responses, and it cannot see rules that live outside the schema: ownership, workflow state, rate limits, or the SKU that must exist in the catalogue. Those need different oracles, such as the ones in [testing API authorization at object, function and property level](https://automationtester.in/blog/automation-tutorials/api-authorization-testing-object-function-property). The generator's output is a reviewable file of cases you already owe the contract, written so that the first failing run tells you something.

## One document, two 3.0 habits

The sample is the tool's own: a 3.1.0 Orders API with three operations, a bearer scheme at the top level and an OAuth scope on `DELETE`. Its request schema keeps two spellings that were correct in 3.0 and are wrong in 3.1:

```
openapi: 3.1.0
# ...
NewOrder:
  type: object
  additionalProperties: false
  required: [sku, quantity, unitPrice, currency]
  properties:
    sku:         { type: string, pattern: '^[A-Z]{3}-[0-9]{4}$' }
    quantity:    { type: integer, minimum: 1, maximum: 100 }
    unitPrice:
      type: number
      minimum: 0
      exclusiveMinimum: true      # 3.0 spelling
    currency:    { type: string, enum: [INR, USD, EUR] }
    giftMessage:
      type: string
      maxLength: 140
      nullable: true              # 3.0 keyword
    contactEmail: { type: string, format: email }
```

The generator lists 38 cases across the three operations and raises one error and two warnings. The error is on `unitPrice`: in JSON Schema 2020-12, which 3.1 schemas follow, `exclusiveMinimum` "MUST be a number". The 3.0 dialect, inherited from Wright Draft 00, defined it as a boolean modifying `minimum`. The first warning is that 3.1 dropped `nullable`; the OAS 3.1.2 base vocabulary is `discriminator`, `xml`, `externalDocs` and `example`, nothing else. The second is that `GET /orders/{orderId}` documents no 400, 422 or 4XX response, so its two input cases can only expect "some 4xx".

The checklist adapts to the error instead of hiding it. Under 3.1 rules the boolean is meaningless, so the boundary case for `unitPrice` is `-0.01` against an inclusive minimum of 0. Change the first line to `openapi: 3.0.3` and the same document yields 37 cases: the boundary case becomes `unitPrice: 0`, rejected because the minimum is exclusive, and the null case for `giftMessage` disappears because 3.0's `nullable: true` permits it. The version line decides what the tests assert, which is why the tool reads it before anything else and treats 3.2 documents with the 3.1 rules.

## What a real validator does with those two lines

A minimal Node server built with Ajv 8.18.0 in 2020-12 mode and ajv-formats 3.0.1 loaded the unfixed document and exited on startup with code 2:

```
compile failed: schema is invalid: data/properties/unitPrice/exclusiveMinimum must be number
```

That is the better outcome. The quieter one is `nullable`. Ajv documents `nullable` as an OpenAPI keyword it supports by default, without additional options, and it applies it in 2020-12 mode too. So a strict 3.1 reading says `giftMessage: null` must be rejected, and Ajv accepts it. The generator marks that case as validator-dependent, with this caveat attached. The fix to the document is two lines:

```
    unitPrice:
      type: number
      exclusiveMinimum: 0
    giftMessage:
      type: [string, 'null']
      maxLength: 140
```

With that applied the generator lists 37 cases, and the only problem left is the undocumented 4xx on `GET`. The downloaded `.spec.ts` holds those 37 plus three control tests, one per operation, that send the valid request and expect success. Credentials are read from `BEARER_AUTH_TOKEN`, `ORDERS_OAUTH_TOKEN` and `ORDERS_OAUTH_TOKEN_WITHOUT_ORDERS_WRITE`; the file contains no token values.

## Forty tests against two validator configurations

The test server validated `POST /orders` bodies with the corrected `NewOrder` schema, checked the path UUID and the `include` enum, and answered 401 and 403 from three random tokens generated per run. It ran in two modes. The first used Ajv's defaults, with no coercion and no data modification. The second used the options Fastify documents as its validator baseline: `coerceTypes: 'array'`, `useDefaults: true`, `removeAdditional: true` and `allErrors: false`. That second mode reproduces Fastify's Ajv settings, not Fastify itself; no Fastify process was involved. The stubs ran under Playwright 1.62.1 on Node 26.0.0 on 2026-10-09.

| Ajv options | Passed | Failed |
| --- | --- | --- |
| Defaults (no coercion) | 40 | 0 |
| Fastify's documented defaults | 36 | 4 |

All four failures expected 422 and received 201, and the server's log shows what each body became before it was accepted:

| Sent | Validated as | Option responsible |
| --- | --- | --- |
| `"quantity": "1"` | `"quantity": 1` | `coerceTypes` |
| `"unitPrice": "12.5"` | `"unitPrice": 12.5` | `coerceTypes` |
| `"giftMessage": 12345` | `"giftMessage": "12345"` | `coerceTypes`, trying `string` first |
| `"unexpectedField": "x"` | property deleted | `removeAdditional` |

Ajv's documentation says `removeAdditional` "modifies original data", and its coercion table converts numbers to strings, numeric strings to numbers and, under the `array` setting, single-item arrays to their item. The handler then receives the converted value. A client that sends `"quantity": "1"` gets an order, and the contract says it should get an error.

## Eight passes that rejected the wrong thing

The 36 passes in the coercing mode are not all what they look like. The server logged the first failing keyword for every rejected body, and for eight cases written to test `type`, a different keyword did the rejecting:

| Case | After coercion | Rejected by |
| --- | --- | --- |
| `sku: 12345` | `"12345"` | `pattern` |
| `sku: null` | `""` | `pattern` |
| `currency: 12345` | `"12345"` | `enum` |
| `currency: null` | `""` | `enum` |
| `contactEmail: 12345` | `"12345"` | `format` |
| `contactEmail: null` | `""` | `format` |
| `quantity: null` | `0` | `minimum` |
| `unitPrice: null` | `0` | `exclusiveMinimum` |

Under Ajv's defaults the same eight were each rejected by `type`. Every one of them is green in both runs, so the status code cannot tell you which world you are in. Delete the `pattern` on `sku` next quarter and `sku: 12345` starts creating orders, though no test about types changed. The fix is to assert where and why the request failed, which the companion article covers under [the status is right and the pointer is empty](https://automationtester.in/blog/automation-tutorials/design-negative-api-tests-from-contract#the-pointer-is-empty). For an Ajv-backed service that returns its errors array, the generated assertion extends by one line:

```
test('rejects when body.sku is 12345 (a number where a string is expected): type: string', async ({ request }) => {
  const response = await send(request, { ...call, body: mutate(call.body, '/sku', 12345) });
  expect(response.status()).toBe(422);
  // Added by hand: the stub cannot know your error format.
  const { errors } = await response.json();
  expect(errors).toContainEqual(expect.objectContaining({ instancePath: '/sku', keyword: 'type' }));
});
```

Against the coercing server that assertion fails with `keyword: 'pattern'`, which is the information you wanted. The generator leaves it out because error bodies are not part of most OpenAPI documents, and a guessed shape would fail everywhere for the wrong reason.

## Deciding which side is wrong

Four failures mean the service and the document disagree. Which one changes is a product decision, and both answers have a cost.

If the document is right, stop coercing request bodies. A JSON body already carries types, so coercion there only hides client bugs. Query strings and path parameters are different: every value arrives as text, and an `integer` query parameter needs coercion to validate at all. Fastify's validation guide shows replacing the compiler with your own Ajv instance through `setValidatorCompiler`, which receives the `httpPart` being validated, so the body can get its own instance:

```
const Ajv2020 = require('ajv/dist/2020');
const addFormats = require('ajv-formats');

const bodyAjv = addFormats(new Ajv2020({ coerceTypes: false, removeAdditional: false, allErrors: false }));
const paramAjv = addFormats(new Ajv2020({ coerceTypes: 'array', useDefaults: true, allErrors: false }));

fastify.setValidatorCompiler(({ schema, httpPart }) =>
  (httpPart === 'body' ? bodyAjv : paramAjv).compile(schema));
```

Turning coercion off breaks any client that has been sending `"1"` and getting away with it. For one release, run the non-coercing validator in report-only mode next to the current one and log the requests it would have refused, so you know who those clients are before they start failing.

If the service is right, the document should say so. Silently stripping unknown properties is a defensible policy, but then `additionalProperties: false` promises a rejection that never comes. Remove it and the generator lists the extra-property case as accepted rather than rejected. Accepting numeric strings is harder to document honestly; `type: [integer, string]` with a pattern says it, at the price of a schema every reader has to decode.

Coercion also opens inputs the generator does not try. Run directly against Ajv with Fastify's options and an integer schema, `"quantity": true` validated as 1, `"quantity": [3]` as 3, `"quantity": "1e2"` as 100, and `"quantity": " 7"` as 7. If you keep coercion, add those four to the file by hand; they are the requests a careless client actually sends.

## Where the output runs out

- Remote `$ref` URLs and `$anchor` references are reported and never fetched, so a schema split across files produces cases only for the parts in the pasted document. Bundle it first.

- `format` cases are marked validator-dependent. JSON Schema 2020-12 says format assertion "MUST be disabled by default", and OAS 3.1.2 treats `format` as an annotation. Ajv with ajv-formats rejected every malformed format value in this run; without ajv-formats, strict Ajv refuses to compile a schema containing `format: email`.

- A pattern without `^` and `$` matches anywhere in the string, because 2020-12 patterns "are not implicitly anchored". The generator lists such a case as accepted instead of writing a test that is guaranteed to fail.

- An undeclared property on a schema that does not set `additionalProperties` is also listed as accepted. Both 3.0.3, where it "defaults to true", and 2020-12 allow it.

- A `mutualTLS` scheme, new in 3.1, gets a checklist line and no stub. The credential is negotiated in the TLS handshake, below the request the stub builds.

- The missing-scope case needs a real token issued without that scope. The stub reads it from an environment variable, and in CI that usually means a second client registration.

## Who gets value from it

Teams with a hand-maintained 3.1 document and a service that validates requests from that document get the most. The run is cheap and the first thing it tests is the validator configuration, which is where the four disagreements above came from. Teams migrating a 3.0 document to 3.1 should paste it before and after changing the version line; the spec-problem list is the migration checklist the version bump does not give you.

It adds little where the document is generated from code annotations after the fact, because then the cases test the generator that wrote the document. It is no substitute for a fuzzer that calls the running API to find crashes, or for the ownership and state cases behind most authorization bugs. If an AI assistant drafted the document, review it as a specification first; [reviewing AI-generated OpenAPI specifications](https://automationtester.in/blog/ai-in-testing/review-ai-generated-openapi-specifications) covers what to check before any case is derived from it.

## Run it against one operation this afternoon

Pick the operation with the largest request schema. Paste the document, fix every error the generator raises, and download the Playwright file. Run the control tests alone first; if a control fails, correct the valid request in `call` before reading anything else. Then run the whole file and record three numbers: passed, failed, and how many failures answered 2xx. A 2xx on a negative case means the service accepted a request the contract forbids, so open the server's validator options before opening a bug. Finally, add the `instancePath` and `keyword` assertion to every type and null case, rerun, and note which keyword each one actually tripped. Keep that list with the spec; it is the evidence that your negative tests are testing what their names say.

## Questions about generated negative cases

### Does Ajv's strict mode catch the 3.0 spellings?

Only one of them. The boolean `exclusiveMinimum` fails schema validation in 2020-12 mode whether strict mode is on or off. `nullable` passes both, because Ajv treats it as a supported keyword rather than an unknown one. Strict Ajv does reject the OpenAPI `example` keyword as unknown unless you register it with `addKeyword('example')`.

### The generated test expects 422 and my API returns 400. Which is wrong?

Neither, until the document says. The generator expects the validation status the operation documents. When an operation lists neither 400 nor 422 it accepts any 4xx and warns, which is the signal to document the response, not to loosen the test.

### What happens to readOnly properties in a request schema?

The two versions disagree. In 3.0.3 a readOnly property in `required` is required on the response only. In 3.1.2 the server "MAY either ignore a readOnly field or treat it as an error", so a test that sends one has no single correct outcome. Decide the policy, then write that test by hand.

## OpenAPI, JSON Schema, Ajv and Fastify references

- [OpenAPI Specification 3.1.2](https://spec.openapis.org/oas/v3.1.2.html): the Schema Object as a 2020-12 superset, the base vocabulary without `nullable`, `format` as an annotation, and the readOnly MAY.

- [OpenAPI Specification 3.0.3](https://spec.openapis.org/oas/v3.0.3.html): the Wright Draft 00 subset, `nullable`, `additionalProperties` defaulting to true, and the integer definition.

- [OpenAPI Specification 3.0.4](https://spec.openapis.org/oas/v3.0.4.html): 1 and 1.0 both counted as integers.

- [JSON Schema Validation, Wright Draft 00](https://datatracker.ietf.org/doc/html/draft-wright-json-schema-validation-00): the boolean `exclusiveMinimum` that 3.0 inherits.

- [JSON Schema 2020-12 Validation](https://json-schema.org/draft/2020-12/json-schema-validation): numeric `exclusiveMinimum`, unanchored patterns, and format assertion off by default.

- [Ajv: type coercion rules](https://ajv.js.org/coercion.html): the conversion table behind the four failures and the eight wrong-keyword passes.

- [Ajv: modifying data during validation](https://ajv.js.org/guide/modifying-data.html): `removeAdditional` modifies the original data.

- [Ajv: JSON Schema support](https://ajv.js.org/json-schema.html): `nullable` supported by default as an OpenAPI keyword.

- [Fastify: Validation and Serialization](https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/): the default Ajv options and `setValidatorCompiler` with `httpPart`.

## Continue reading on AutomationTester.in

- [Design Negative API Tests from the Contract](https://automationtester.in/blog/automation-tutorials/design-negative-api-tests-from-contract)
- [API Contract Testing with Playwright and JSON Schema](https://automationtester.in/blog/automation-tutorials/api-contract-testing-playwright-json-schema)
- [Review an AI-Generated OpenAPI Description Before You Publish It](https://automationtester.in/blog/ai-in-testing/review-ai-generated-openapi-specifications)
- [Detect Breaking API Changes Before Consumers Do](https://automationtester.in/blog/automation-tutorials/detect-breaking-api-changes-before-consumers)
- [Build Deterministic Python API Test Data Factories](https://automationtester.in/blog/automation-tutorials/python-api-test-data-factories-deterministic)

Source: [Generate OpenAPI 3.1 Negative Tests From the Spec, Then Check Your Validator](https://automationtester.in/blog/tools-reviews/openapi-31-negative-tests-from-the-spec) by Shashank Rawlani.
