Validating API requests against OpenAPI in Apache APISIX

How the oas-validator plugin rejects malformed API requests at the gateway against an OpenAPI 3.x document, and how to roll it out safely.

On this page

Validating API requests against OpenAPI in Apache APISIX before they reach services

Services that accept malformed requests have to reject them in their own code, and every service repeats that work. A missing required field, a wrong content type or an unexpected query parameter can reach a backend, consume its resources and fail deep in business logic. The oas-validator plugin in Apache APISIX lets the gateway enforce the published OpenAPI 3.x contract before a request is forwarded, so each service sees only traffic that matches its declared interface. The plugin checks the request method, the path, query parameters, headers and the body against an OpenAPI 3.x document. You supply that document inline in the route configuration or point the plugin at a URL. Failed requests receive a 400 response by default. You can also set the plugin to log failures without blocking them, which is the usual first step on an existing API.

Gateway validation and validation inside each service answer different questions. The gateway is the right place to reject structurally invalid traffic uniformly across many routes, keep abusive or broken clients away from upstreams, and produce consistent logs for security review. Service-side validation still handles business rules that a schema cannot express, such as whether an account can perform an action or whether two values are consistent with stored state. Plan both layers and document which rules each one owns. Before enabling blocking mode, confirm with your API owners that the OpenAPI document matches what the service really accepts, since a stale spec will turn the gateway into a source of false rejections. Log-only rollout exists to surface exactly those mismatches. Check the current option names and behavior in the plugin documentation for your APISIX version.

Which oas-validator settings fit which situation

This table compares inline specs, remote specs fetched by URL, enforcement and log-only mode, and the 3,600-second remote cache lifetime. Read each row against your release process and how much spec upkeep your team can absorb, since the operational effort differs more than the plugin configuration does.

SettingWhen it fitsOperational effortWhat to confirm first
Inline specSmall APIs owned by one team, where the spec ships in the same repository as the route configurationSpec changes travel with gateway config changes, so reviews and rollbacks happen togetherConfirm the spec size is manageable in your configuration tooling and pipelines
Remote spec by URLServices that publish their own OpenAPI document from their build and expose it on an internal addressThe gateway depends on the spec URL being reachable, and spec updates reach the gateway on the cache cycleConfirm the URL is reachable from every APISIX node and who owns its availability
Enforce mode (default rejection)Routes whose consumers already send conforming requests and where malformed traffic must stop at the edgeExpect a spike in 400 responses if clients or specs drift, so alerting and client communication need planningConfirm client teams accept the validation contract before switching enforcement on
Log-only modeInitial rollout on existing production routes, to measure how much traffic would fail validationRequires someone to review logs and decide on each finding before enforcement is enabledConfirm your logging pipeline captures validation outcomes for the review period
Remote cache lifetime of 3,600 secondsSpecs that change on a release cadence measured in hours or days, where some delay is acceptableA spec change can take up to the cache lifetime to take effect, so releases need a planned cutover windowConfirm with service owners how quickly a new spec must be enforced after deployment
Body and schema validationAPIs where payload shape is the main risk, such as write endpoints accepting structured dataSchema coverage in the spec is the limit, so incomplete specs leave gaps that the gateway cannot detectConfirm the spec defines request bodies and schemas for the endpoints you protect

Which parts of a request the validator checks and where it stops

The oas-validator plugin checks the request method, path, query parameters, headers and body against the OpenAPI 3.x document you give it, either inline or by URL. Anything the spec does not describe is outside what the plugin can judge, so the validator is only as strict as the document behind it. Before enabling it on a route, confirm that every operation the gateway exposes has an entry in the spec, with the correct method and path template. A missing operation is not a rejected request, it is an unvalidated one, and a reader scanning the gateway logs will not see that gap unless they look for it.

Schema coverage is the next check. For each operation, confirm that query parameters, request headers and request bodies are declared, that required fields and value constraints match what the services actually accept, and that each allowed content type appears under the request body. A body declared as application/json will not validate an application/x-www-form-urlencoded request in the same way, so clients using other types may be rejected or passed through depending on how the spec is written. Authentication headers such as Authorization or an API key header often live in the gateway's authentication plugins rather than the spec. Decide whether the spec documents them, because an undocumented header will not be checked by the validator and a documented one must match the header name your clients send.

Validation depends on the spec being accurate and complete, and the plugin cannot detect drift on its own. Ask the API owners who maintain the OpenAPI document how changes to services are reviewed and whether the spec is versioned with the code, then test a sample of real traffic against the spec before enforcing rejections. Confirm the validator's behavior for paths the spec does not list, since your team should decide whether those requests are rejected or only logged. Any answer you cannot verify in your own environment should go into the rollout plan as an open item for the owner to confirm, with the official oas-validator plugin documentation used as the reference for plugin behavior.

How to set up OpenAPI validation on a route

This sequence takes a route from having no request checks to enforcing an OpenAPI 3.x contract at the gateway. It ends with a route that rejects non-conforming requests, backed by a log-only period that shows which real traffic would have been blocked.

  1. Obtain and check the OpenAPI document

    The API owner and the platform team confirm which OpenAPI 3.x document describes the live behavior of the service, either an existing file exported from the service repository or a new one written for this purpose. Check that the document validates with a standard OpenAPI linter, that the paths and methods match the routes you plan to protect, and that the server URL and security definitions are correct. You know this step is done when the team agrees the document describes what the service actually accepts, and the file is stored in version control with a named owner.

  2. Decide where the spec is served from

    Choose between an inline specification stored in the plugin configuration and a remote URL that the gateway fetches. Inline specs keep the gateway independent of another service but must be updated with the route configuration. A remote URL lets the spec change without editing the route, and the oas-validator plugin caches remote specs for 3,600 seconds, so changes take up to that long to take effect. Confirm with the API owner which option matches your release process. You know this step is done when the chosen source is written down with its owner and update path.

  3. Attach the oas-validator plugin to a route

    The platform engineer adds the oas-validator plugin to a test route in the Admin API or the configuration file used by your deployment, with the specification and the validation mode set to log only. Keep the route scoped to one service at first and leave the upstream and other plugins unchanged so any later rejection can be traced to the validator. Send a few requests you know are valid and a few you know are invalid, such as a missing required field or a wrong content type, and confirm the gateway still forwards the traffic. You know this step is done when the route applies the configuration without errors and the test traffic reaches the upstream as before.

  4. Run log-only mode against real traffic

    Leave the route in log-only mode for a period your team agrees on and let production or staging traffic flow through it. The gateway logs each request that fails validation while still forwarding it, so no client is affected by the change. Make sure the gateway access and error logs are shipped to the team's logging system and that someone can search them by route. You know this step is done when the logs contain validation results for a representative mix of endpoints, methods and client types, not only the happy path.

  5. Review rejections and fix the spec or the clients

    The API owner and the security or platform reviewer go through the logged failures and sort each one into one of three groups: a genuine malformed request from a client, a field the service accepts but the spec does not describe, or a spec error. Fix the spec where it is wrong, ask client teams to correct requests that are truly invalid, and record any intentional exceptions with a reason. Rerun the test requests from the earlier step to confirm the fixes behave as expected. You know this step is done when every logged failure has an owner and a recorded decision, and the remaining failures are all expected.

  6. Set body size limits and confirm the validator scope

    Before enforcement, confirm which parts of each request the validator checks in your version, including method, path, query parameters, headers and body, and document any part that is not covered so other controls can handle it. Set request body size limits at the gateway or in the route configuration, because a validator that reads a very large body adds processing cost and can be used to exhaust resources. Ask the vendor or project documentation for the exact behavior of the limit in your APISIX version. You know this step is done when the team has a written list of checked and unchecked request parts and a tested body size limit.

  7. Switch the route to enforcement

    Change the validator mode from log only to reject, so that non-conforming requests receive a 400 response by default, and apply the change during a window agreed with the service owner. Send one valid and one invalid request to the route and check that the valid request reaches the upstream and the invalid one is rejected before it does. Watch the error rate and the logs for the first period after the change and keep the log-only configuration ready to restore. You know this step is done when enforcement is confirmed with both test requests and the monitoring shows no unexpected rise in rejected valid traffic.

  8. Keep the spec in sync with each release

    Add a step to the service release process so that every change to an endpoint, parameter or body schema updates the OpenAPI document and the gateway configuration in the same change set. Run the linter and a validation test against the route in the pipeline before the release is promoted. Assign an owner for the spec and review it whenever the service changes. You know this step is done when a deliberately mismatched spec fails the pipeline and a matching release passes without manual intervention.

Body size limits and other controls to pair with validation

Request validation is one control among several at the gateway. Body size limits, rate limits and the order in which plugins run all change what a rejected or accepted request costs your services. Treat each as its own policy, test how they interact on a non-production route, and confirm the exact behavior in the APISIX version you run.

Set a maximum request body size

A body size limit caps how much data one request can send through the gateway to your services. Without one, a client can send payloads your upstream services were never sized to handle. Set the limit per route using the largest legitimate payload each API accepts, and record that value next to the OpenAPI spec so the two stay aligned. Confirm in your APISIX version which mechanism enforces the limit, which status code it returns, and whether it applies to chunked requests that carry no Content-Length header.

Check the order of size and schema checks

A size limit and a schema check answer different questions. The size limit asks whether the body is too large to accept, while the validator asks whether the body matches the declared schema. Which runs first decides what the client sees for an oversized request and what gets logged during a rollout. Send both kinds of invalid request to a staging route, record each response, and confirm the order in your version against the plugin documentation before you write client guidance.

Keep rate limits as their own policy

Validation confirms that a request is well formed. It says nothing about how often a client may send requests. A fully valid request can still exhaust a backend, so rate and quota limits need their own gateway policy, with their own owner, thresholds and dashboards. Choose the key that identifies the caller, such as a consumer or client identifier. Confirm in your version whether requests rejected by validation still count against those limits, because the answer changes how much headroom legitimate clients keep.

Keep size limits enforced during rollout

In log-only mode the validator records failures but lets requests through, so the body size limit must remain an enforced control. Teams sometimes treat a log-only rollout as a pause on all request controls, which lets oversized bodies reach services for weeks. Turn the size limit on from the first day, review validator logs for false positives, and switch the validator to rejection only after the logs stay clean. Record the switch date in the change ticket so the rollout has an auditable end.

Keeping OpenAPI specs in sync with service releases

The main risk in OpenAPI request validation is drift: the spec describes an older version of the service than the one running. When a team ships a new field, a new path or a changed enum without updating the spec, the oas-validator plugin keeps checking requests against the old contract. Legitimate calls then fail with 400 responses, or, if the route runs in log-only mode, quietly appear as violations in logs that nobody reads. Drift also works in the other direction: a spec that still allows a field the service has removed lets bad requests through. Before go-live, confirm with each service owner which artifact is the source of truth, usually the spec generated from code or the hand-maintained file in version control, and record which one the gateway loads.

The delivery method changes how fast a spec change takes effect. When the plugin reads an inline spec, the new contract reaches the gateway only when the route configuration is updated. When it reads a spec by URL, the plugin caches the remote document for 3,600 seconds, so a spec published at the URL may not be enforced for up to an hour on each gateway. That delay can cause a window where new requests are rejected or accepted under the wrong contract. Ask the platform team how route updates are pushed in your deployment mode, and test the cache window in a non-production environment before relying on it for a rollout.

A workable release process updates three things together: the spec, the route that references it and the log-only review. The service pipeline publishes the spec alongside the build, and a merge request that changes an endpoint must also change the spec, which a contract test can enforce. The route change is deployed first in log-only mode so the team can review violations from real traffic against the new contract. Only after that review, and after a clean period agreed by the owners, does enforcement return to rejection. Rollback should revert the spec and the route together, and the runbook should name who approves each step, so that a release never leaves the gateway enforcing a contract the service no longer serves.

Security and operational considerations for spec-based validation

How much should we trust a remote OpenAPI spec loaded by URL?

Treat a remote spec as configuration that can change which requests are allowed, so its source deserves the same control as any gateway policy. The oas-validator plugin can load a spec by URL and caches it for 3,600 seconds, so a bad or tampered document can keep rejecting or accepting traffic for up to an hour after the source changes. Load specs only from a location your team controls, pin the expected version in your release process, and confirm with your own review step that the document matches the service contract before it reaches production. Where the spec is sensitive or must not change unannounced, an inline spec kept in version-controlled gateway configuration removes the remote dependency entirely.

How do we protect the endpoint that serves the OpenAPI document?

Serve the spec from an endpoint that is reachable by the gateway but not by the public internet, and restrict who can publish to it. The spec describes your internal routes, parameters and schemas, so it is useful reconnaissance for an attacker even though it contains no secrets. Use network controls to limit read access to the gateway's address range, require authentication on the hosting service where your platform supports it, and log changes to the file or object. Confirm with your platform team how the gateway reaches the endpoint, including whether TLS certificates are verified, since a plaintext or unverified fetch exposes the spec to tampering in transit.

What happens to live traffic if the spec is wrong?

A wrong spec blocks valid traffic in enforcement mode and passes invalid traffic when a route is not covered, so a spec error is an outage risk, not only a documentation problem. Common causes include a missing optional field marked as required, a schema that is stricter than the service actually accepts, an enum that lags behind a new release, or a path template that does not match the route. Run the new spec in log-only mode against real traffic first, review what would have been rejected, and only then switch to rejection. Keep a tested way to disable the plugin or revert the spec reference, and agree the rollback owner before the change window opens.

How should rejected requests be logged without exposing sensitive payloads?

Log the rejection reason, route, method, status and a request identifier, and keep request bodies and sensitive headers out of the default log stream. Validation errors often echo parts of the offending value, so a rejected request containing a card number, national identifier or credential could end up in a log store with broader access than the source system. Configure your log pipeline to drop or mask body fields and authorization headers, set retention that matches your data classification, and restrict who can query gateway logs. Confirm with your security and privacy teams which fields count as sensitive for your data, since that list is specific to each organization.

Who should own changes to the OpenAPI spec?

The service team that owns the API should own its spec, and the platform or gateway team should own how the spec is loaded and enforced. Tying the spec to the service release keeps the contract and the implementation in step, so a change to a route, parameter or schema goes through the same review and tests as the code. The gateway team reviews changes that affect enforcement mode, cache settings and shared error responses. Write this split down in your change process, name a reviewer for each side, and require that a spec change and its matching service change ship together or in a documented order.

How do we keep specs in sync with service releases?

Generate or publish the spec as part of the service build, then deploy the gateway configuration that references it in the same pipeline. Manual copies drift quickly, and a stale spec either rejects new valid fields or accepts fields the service no longer handles. Add a check that compares the spec with the service's own contract tests, run validation in log-only mode on staging with representative traffic, and record which spec version each gateway route uses so incidents can be traced. Ask your team whether their current stack can produce the spec automatically, because that determines how much of this is pipeline work and how much is manual review.

Can our own team operate spec-based validation, or do we need a partner?

A team with gateway operations experience can run spec-based validation in-house, and the deciding factors are the number of APIs, how often their contracts change, and how much review capacity exists. The main effort is not the plugin configuration but the ongoing work of keeping specs accurate, testing log-only results, and handling exceptions for legacy routes. DeployOpen plans, implements and documents these controls inside the client's own infrastructure under a written, fixed scope, and ongoing support is available as a retainer. Ask any partner, including DeployOpen, how they would handle spec ownership, rollback and log redaction in your environment before agreeing scope.

Limits to confirm in your environment before rollout

Validation rules are only as reliable as the gateway's reading of your spec and your traffic. These checks sit between a passing lab test and a safe production switch. Work through each one with your own specs, payload sizes and APISIX release, and record the results before you move any route from log-only mode to enforcement.

Supported OpenAPI feature set

The plugin validates requests against OpenAPI 3.x documents, but not every schema keyword, format, security definition or reusable component may be enforced the way your spec author expects. Check the plugin documentation for the keywords and constructs it evaluates, then compare that list with what your specs use. Run your full spec through a test suite of valid and invalid requests, and record every invalid request that passes.

Large and streamed request bodies

Body validation needs the complete payload, so large uploads and streamed requests can behave differently from small JSON calls. Confirm how the plugin handles chunked transfers, what happens when a body exceeds the size limit you configure, and whether a rejected request ever reaches the upstream service. Test with payloads at the limit and just above it, and watch memory use on gateway nodes during those runs.

Latency and CPU under load

Each validated request spends time matching the path, reading the body and checking it against the schema. The cost depends on spec size, body size and request rate, so a small test cluster will not predict production behavior. Replay recent traffic at peak volume with and without the plugin, then compare tail latency, gateway CPU and error rates before enabling enforcement on busy routes.

Remote spec fetching and caching

When the spec is loaded from a URL, the gateway keeps a cached copy for a fixed period. A spec change published during that window is not seen until the cache expires, so a new endpoint may be rejected or a retired constraint may still be enforced. Confirm what happens when the spec URL is unreachable at startup or at refresh, and decide whether critical routes should carry an inline copy of the spec instead.

Behavior in your APISIX release

Validation behavior can change between APISIX releases, and the downloads page does not mark any release as long-term support. Pin the exact version you deploy, read the release notes for changes to this plugin, and rerun your validation suite after every upgrade. Confirm that your chosen release contains the oas-validator behavior your tests depend on, and plan the upgrade cadence before rollout begins.

What does it cost to add OpenAPI validation to APISIX?

What drives the cost of adding OpenAPI validation to APISIX?

The main drivers are how many routes need validation, how complete and accurate the existing OpenAPI documents are, and how many services use them. Each route needs its spec mapped to the correct path and method, and every mismatch between spec and running service adds investigation time. Costs are set by the written scope, so a quote should list the routes, specs and environments in scope. No price is given here, and DeployOpen does not publish a price list.

Does the spec quality change how long validation takes to set up?

Yes. A spec that matches the deployed API can be wired in with limited rework, while a spec written after the fact or left behind by code changes often needs correction before validation is safe to enforce. Work usually includes checking each operation for missing parameters, incorrect schemas and undocumented headers. Ask the client's API teams how specs are maintained today and whether they are generated from code or edited by hand, since that shapes the rework.

How long does it take to reach a safe enforcement mode?

The time depends on the route count, spec readiness and how many teams must review log output before enforcement. A common sequence is to deploy in log-only mode, review rejected requests with the owning teams, correct either the spec or the client, and then switch to rejection. No duration is given here. Ask any partner to state the phases, the criteria for leaving log-only mode and the owner who signs off each step.

What does the work need from our API and platform teams?

The API teams provide current OpenAPI 3.x documents, know which versions are live, and answer questions about intended behavior for edge cases. The platform team provides access to the APISIX Admin API or configuration files, the environment where the plugin runs, and a way to publish spec updates. Both teams review log-only results. Agree these responsibilities in the scope so that delays on one side do not stall the whole rollout.

Can our in-house team add OpenAPI validation to APISIX by itself?

A team that already runs APISIX and maintains accurate OpenAPI documents can usually handle a small number of routes internally. The harder parts are keeping specs in sync across releases, tuning body size limits for large payloads, and coordinating log-only review across several teams. Compare your team's capacity for those tasks with the route count. A fixed-scope engagement can cover the setup and handover while your team keeps ownership of the specs.

Which costs are one-time and which recur after go-live?

One-time costs include mapping routes to specs, configuring the plugin, testing log-only results and writing the runbook. Recurring costs come from updating specs with each API release, reviewing rejection logs, and revalidating after APISIX upgrades. Remote specs are cached for 3,600 seconds according to the oas-validator documentation, so cache behavior is a factor when specs change. Ask whether ongoing support is included or billed as a retainer.

What should we ask for in a fixed-scope quote for this work?

Ask the partner to list:

  • the routes and OpenAPI documents in scope, with their versions
  • which parts of each request are validated, and which are excluded
  • the environments covered and the sign-off steps for log-only and enforcement
  • body size limits and the test cases used to confirm them
  • the handover documents and any recurring support terms

Fixed-scope quotes are agreed in writing before work starts, so every item should appear there.

Which APISIX deployment details can change the effort?

The deployment mode affects how configuration reaches the gateway. Traditional mode uses etcd and the Admin API, decoupled mode shares one etcd cluster between control and data planes, and standalone mode reads conf/apisix.yaml or conf/apisix.json and hot-reloads changes each second. Each mode changes how the validation settings are deployed and tested. Confirm which mode runs in each environment before estimating work, and check the APISIX version in use with the project's downloads page.

How DeployOpen scopes and delivers OpenAPI validation

DeployOpen scopes OpenAPI validation as a fixed-scope engagement with the written agreement fixing the route list, the OpenAPI documents to be enforced, and the rollout stages before any configuration changes. The scope names each route group, the oas-validator settings planned for it (inline spec or remote spec_url, reject_if_not_match or log-only behavior, and body size limits), and the owner of each spec. Acceptance criteria are written down too, such as which malformed request classes must return 400 in a test environment and which must only be logged during the observation period. Your team confirms which routes are public, which are internal, and which services already fail on bad input, because those answers decide the rollout order.

DeployOpen implements and tests the work inside your own infrastructure, including the APISIX deployment, the Admin API access path, and the environments where specs are fetched. Testing covers valid requests from your known clients, deliberately malformed requests for each validated part (method, path, query, headers and body), and oversized bodies. Remote spec fetching is tested against the 3,600-second cache behavior so your team knows how long a published spec change takes to reach the gateway. Where the deployment uses decoupled or standalone mode, the spec delivery path is confirmed with your operators as part of the build.

Spec drift is the main ongoing risk, so DeployOpen offers retainers that cover spec synchronization with each service release, reviews of log-only findings before enforcement is switched on, and APISIX upgrade checks against the validator configuration. Ask any provider, including DeployOpen, to state in the quote who owns the spec repository, who approves a spec change, and what happens when a service ships before its spec is updated. Those answers, not the plugin itself, usually determine whether the validator keeps protecting the right endpoints six months after go-live.

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.