A glowing schema diagram beside a gateway routes data packets and diverts invalid ones.
Valid data flows past rejected requests

How to Validate SaaS API Requests with OpenAPI Schemas

To validate incoming SaaS API requests, match each request to an OpenAPI operation, parse its inputs, and reject anything that violates the declared schemas. Put this check before business logic so invalid data can’t trigger database writes or billing actions.

OpenAPI request validation catches missing fields, incorrect types, and unsupported values. It doesn’t prove that a caller owns a tenant’s records or can change a subscription.

Start with one endpoint and its contract, then connect that contract to your server’s request pipeline.

Key Takeaways

  • Validate declared parameters and request bodies, including required fields, types, and allowed values.
  • Match your validator to the OpenAPI version and schema dialect your contract uses.
  • Keep authentication, tenant authorization, and business rules separate from schema validation.
  • Test rejected requests through HTTP and confirm they produce no business side effects.

Step 1: Define What OpenAPI Request Validation Covers

Validation starts by matching the HTTP method and path to an operation. For example, POST /subscriptions and GET /subscriptions have separate contracts.

Validate parameters after parsing them

OpenAPI describes parameters in four locations: path, query, header, and cookie. Each parameter can define its type, allowed values, and other constraints.

Path parameters are always required. Other parameters become mandatory when their definitions set required: true.

Serialization matters because HTTP parameters usually arrive as text. An integer query parameter needs appropriate parsing, while arrays must follow the contract’s serialization rules. A comma-separated value and repeated query keys aren’t automatically interchangeable.

Use middleware that understands OpenAPI parameter serialization rather than passing every raw value directly to a JSON Schema validator.

Match the body to its media type

Request bodies declare supported media types under requestBody.content. The OpenAPI request-body specification defines how these media types connect to schemas.

A JSON request might require an object with a subscription plan and seat count. Multipart requests need compatible upload parsing as well as validation.

Body presence and property presence are separate rules. requestBody.required: true requires a body; the schema’s required array identifies mandatory properties within it.

Also apply payload-size limits. Schema constraints don’t replace limits on bytes received or uploaded files.

Step 2: Match the Schema Version to Your Framework

Choose the contract version and validation approach together. A valid specification file doesn’t guarantee that every library interprets its schemas correctly.

Understand OpenAPI 3.0 versus 3.1

OpenAPI 3.0 uses its own schema model based on an older JSON Schema subset. OpenAPI 3.1 aligns with JSON Schema Draft 2020-12.

Nullability illustrates the difference. In 3.0, a string can use nullable: true. In 3.1, it can use type: [string, "null"].

The OpenAPI 3.1 schema rules also treat format as an annotation by default. An email format therefore needs explicit enforcement by the selected validator.

Don’t pass an entire OpenAPI document to a generic JSON Schema validator. A request adapter must first select the operation, deserialize parameters, and choose the appropriate body schema.

Choose contract-first or code-first validation

With Express, express-openapi-validator provides middleware for validating requests against an OpenAPI document. Ajv is another useful component, but alone it doesn’t provide HTTP operation matching.

FastAPI takes a code-first approach: request models use Pydantic validation, and the framework generates OpenAPI documentation.

That distinction matters when another team supplies the contract. Generated documentation doesn’t automatically prove that your implementation matches an independently maintained specification. Avoid keeping two manually edited definitions of the same rules.

Step 3: Write a Small, Explicit Request Contract

Save this contract as openapi.yaml. It uses OpenAPI 3.0.3 syntax for a subscription-input endpoint:

openapi: 3.0.3
info:
  title: Subscription API
  version: 1.0.0
paths:
  /subscriptions:
    post:
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [plan, seats]
              properties:
                plan:
                  type: string
                  enum: [starter, pro]
                seats:
                  type: integer
                  minimum: 1
      responses:
        '200':
          description: Input accepted

The enum restricts plan values. minimum: 1 rejects zero and negative seat counts, while type: integer rejects fractional values.

Here, additionalProperties: false rejects undeclared body properties. This catches misspellings, but it also makes adding client-supplied fields a compatibility decision.

Keep the contract focused on structural rules. Whether an account can purchase a particular plan belongs in application logic.

The response describes acceptance only. The implementation below validates input without creating a subscription, charging a card, or writing records.

Step 4: Attach the Contract to Express

Install the dependencies with npm install express express-openapi-validator. Save this CommonJS example as server.cjs beside the schema:

const express = require('express');
const path = require('node:path');
const OpenApiValidator = require('express-openapi-validator');


const app = express();


app.use(express.json({ limit: '100kb' }));


app.use(OpenApiValidator.middleware({
  apiSpec: path.join(__dirname, 'openapi.yaml'),
  validateRequests: true,
  validateResponses: false
}));


app.post('/subscriptions', (req, res) => {
  res.status(200).json({ accepted: true });
});


app.use((err, req, res, next) => {
  const status = err.status || 500;


  if (status >= 500) {
    return res.status(500).json({ code: 'internal_error' });
  }


  res.status(status).json({
    code: 'invalid_request',
    message: 'The request could not be accepted.',
    errors: (err.errors || []).map(({ path, message }) => ({
      path,
      message
    }))
  });
});


app.listen(3000);

The JSON parser runs first so the validator receives a parsed body. apiSpec loads the contract, while validateRequests enables incoming-request checks.

validateResponses: false leaves outgoing-response validation disabled. It doesn’t reduce the request checks.

The route handler appears after validation. The final four-argument middleware handles errors instead of exposing stack traces.

Start the server with node server.cjs, then send:

curl -i http://localhost:3000/subscriptions 
  -H 'Content-Type: application/json' 
  --data '{"plan":"pro","seats":3}'

The endpoint returns HTTP 200. Changing seats to 0 should produce a validation rejection before the handler runs.

This example has no authentication. Add authentication and tenant authorization before exposing a real subscription operation.

Step 5: Place Validation Before Business Side Effects

For an ordinary authenticated JSON endpoint, apply connection-level protections and request-size limits first. Then parse the body, authenticate the caller, validate inputs, and apply resource-level authorization before business processing.

Some authorization checks require validated identifiers, so their exact position depends on the endpoint. For example, confirming tenant membership can happen early, while checking ownership of a requested record requires that record’s identifier.

Schema validation can’t establish either relationship. A well-formed tenant ID remains untrusted until the server checks access.

Webhook endpoints need a different parsing arrangement when signatures cover the original request bytes. Preserve those bytes and verify the signature according to the provider’s protocol before processing the parsed event.

A payload can pass schema validation and still be forged, unauthorized, or a duplicate delivery.

After validation and authorization, apply business rules such as seat availability or permitted subscription transitions. For retryable writes, enforce idempotency separately. A schema-valid request can still repeat an operation that already committed.

Step 6: Return Actionable Errors Without Leaking Data

Use a consistent response envelope with a stable application error code and field-level details. Clients should be able to identify which input failed without parsing a stack trace.

For the sample endpoint, the useful explanation is that seats must be an integer greater than or equal to one. Missing-property errors should name the required property.

OpenAPI doesn’t mandate one validation status or error envelope. Choose a documented policy and keep it consistent. FastAPI, for example, returns HTTP 422 for request-validation errors by default, with details in a detail field.

Preserve meaningful HTTP distinctions. Malformed JSON, an unsupported media type, and an oversized body shouldn’t all become an internal-server error.

In logs, record the operation, failed rule, and request identifier. Attach tenant identity only when authentication established it. Exclude credentials, authorization headers, and complete customer payloads.

Keep unexpected server failures generic for callers, but retain sanitized diagnostic information internally.

Step 7: Test the Contract and the Business Outcome

Runtime validation protects live traffic. Contract and integration tests catch problems before customers encounter them.

Use contract checks to detect incompatible changes

Run specification checks in CI so malformed documents fail before deployment. Then compare contract revisions with tools such as oasdiff.

Making an optional property required, narrowing an enum, or increasing a minimum can break existing clients. Treat stricter validation as an API compatibility change, even when the endpoint path stays the same.

Pact can capture consumer expectations when you control both sides of an integration. However, schema comparisons and consumer contracts still need runtime tests because structural compatibility doesn’t prove unchanged business behavior.

Exercise the middleware through HTTP

Test a valid request, a missing body, malformed JSON, an unknown plan, and a seat count below the minimum. Also test unsupported content types and undeclared properties.

Send requests through the actual middleware stack. Calling a schema function directly won’t expose incorrect routing or parser order.

For every rejected write, assert that no database record, billing action, or queued job was created. Separately test cross-tenant access and duplicate requests.

Keep fixtures for supported SDKs and important no-code workflows. A changed field requirement can break a Zapier mapping even when your own interface still works.

For stricter rules on existing endpoints, measure would-be failures before enforcing them broadly. Keep authentication and authorization fully enforced during that rollout.

Frequently Asked Questions

Does a valid OpenAPI document validate live traffic?

No. The document describes the contract, but runtime middleware, framework validation, or equivalent gateway enforcement must apply it to incoming requests. Documentation hosting alone doesn’t reject invalid traffic.

Can schema validation replace integration tests?

No. It checks declared input constraints, not the resulting business outcome. Integration tests must still cover tenant isolation, database changes, downstream failures, and retries. A successful status code doesn’t prove that a request produced the correct stored state.

Keep the Contract Close to the Request Pipeline

Effective OpenAPI request validation connects one maintained contract to the code that accepts customer traffic. Its main benefit is predictable rejection before invalid input reaches business operations.

Start with one write endpoint and test both acceptance and rejection through HTTP. Then expand coverage while preserving supported client behavior.

Keep schema correctness separate from authorization and business correctness. Together, those controls make the API safer without asking one validation layer to solve every problem.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *