REST API Request Validation Example: JSON Schema, Errors and Security Best Practices
REST API Request Validation Example & Best Practices
API Input Security

REST API Request Validation Example: JSON Schema, Errors and Security Best Practices

Request validation should fail invalid data before it reaches business logic. Validate the media type and body size first, parse with a safe parser, enforce a schema, reject unexpected fields when the contract requires strictness, then apply business rules and authorization. Validation is not sanitization and it is not a substitute for object-level access control.

Implementation guideAPI Example
Contract layerJSON Schema / typed model
Transport checkContent-Type + body size
Error formatProblem Details
Security ruleAllowlist, do not trust input

REST API Request Validation Example

Consider an endpoint that creates a transfer. The API should reject invalid structure and constraints before executing the transfer:

POST /v1/transfers HTTP/1.1
Content-Type: application/json

{
  "source_account_id": "acc_100",
  "destination_account_id": "acc_200",
  "amount": 125.50,
  "currency": "USD"
}

A validation model can require the IDs and currency, enforce amount type/range, cap string lengths, restrict currency to supported values, and reject additional properties if strictness is part of the contract.

The Five Layers of API Request Validation

  1. Transport constraints: request/body size, header size, supported methods and supported content type.
  2. Parsing: use a safe JSON/XML/multipart parser and reject malformed syntax.
  3. Schema validation: required fields, types, arrays, lengths, ranges, formats and unknown properties.
  4. Business validation: domain rules such as “source and destination cannot be the same.”
  5. Authorization: independently verify that the caller is allowed to use the referenced objects and perform the action.
Do not combine authorization with validation. A syntactically valid account_id can still belong to another customer.

JSON Schema API Validation Example

JSON Schema 2020-12 is the current published JSON Schema specification. A simplified request schema might look like:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["source_account_id", "destination_account_id", "amount", "currency"],
  "additionalProperties": false,
  "properties": {
    "source_account_id": {"type":"string", "minLength":1, "maxLength":64},
    "destination_account_id": {"type":"string", "minLength":1, "maxLength":64},
    "amount": {"type":"number", "exclusiveMinimum":0, "maximum":1000000},
    "currency": {"type":"string", "enum":["USD","EUR","GBP"]}
  }
}

Schema validation is strongest when the same contract informs documentation, test generation and server-side validation. But business rules and permissions still belong in application logic.

JSON Schema format needs deliberate validator configuration. In Draft 2020-12, format handling is separated into annotation and assertion vocabularies. Do not assume that adding "format": "email" or "format": "date-time" automatically rejects invalid values in every validator.

REST API Validation Error Response Example

Use the HTTP status code to describe the protocol-level outcome and a structured body to explain the validation problem. RFC 9457 defines application/problem+json:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Request validation failed",
  "status": 422,
  "errors": [
    {"field":"amount", "code":"maximum", "message":"Must be less than or equal to 1000000"},
    {"field":"currency", "code":"enum", "message":"Unsupported currency"}
  ]
}

Use 400 Bad Request for malformed syntax or according to your chosen validation contract. 422 Unprocessable Content is useful when the representation is syntactically valid but cannot be processed because its instructions or values are invalid. Be consistent across the API.

Keep validation details useful but bounded: return stable machine-readable codes and field locations, but avoid echoing secrets, full rejected tokens, database details or parser internals into the response.

Should a REST API Reject Unknown JSON Fields?

Strict contract

Reject unknown properties. This catches client typos early and reduces mass-assignment risk when the public write model is narrow.

Forward-compatible contract

Ignore unknown properties only when that behavior is intentional, documented and safe. Generated clients and staged migrations may influence the decision.

Do not deserialize arbitrary client JSON directly into an internal persistence/entity model. Define a public request DTO/schema that contains only writable fields.

REST API Validation Security Best Practices

  • Do not trust any parameter or object, including headers, path variables and nested JSON.
  • Validate length, range, format and type.
  • Define request-size limits and reject oversized bodies early.
  • Require supported request content types and reject unsupported ones with 415 Unsupported Media Type.
  • Use secure parsers; harden XML parsing if XML is supported.
  • Parameterize database queries after validation; validation alone does not prevent injection.
  • Log repeated validation failures as a potential abuse signal without storing sensitive payloads unnecessarily.

These recommendations align with the OWASP REST Security Cheat Sheet. For broader API controls, see REST API endpoint security best practices.

For multipart bodies and file-specific validation, see REST API file upload examples and security best practices.

Schema Validation vs Business Validation

A schema can prove that amount is a positive number. It cannot prove the source account has enough balance, the caller owns it, the transfer is within a user-specific limit, or the destination is permitted. Keep these layers separate so error handling and security reviews remain clear.

QuestionValidation layer
Is amount a number greater than zero?Schema / structural validation
Is currency supported by this endpoint?Schema or domain validation
Does the source account exist?Domain lookup
Does the caller control the source account?Authorization
Would this exceed the caller’s daily limit?Business rule / risk policy

Common API Request Validation Mistakes

  • Validating only on the frontend.
  • Trusting framework deserialization without explicit field constraints.
  • Using regex as the only defense against SQL or command injection.
  • Silently accepting misspelled fields that the client thinks were applied.
  • Returning internal exception messages or stack traces for validation failures.
  • Performing expensive database work before rejecting an obviously oversized or malformed request.

Validate Path, Query and Header Inputs Too

Request validation is broader than the JSON body. Path parameters can contain unexpected encodings, query parameters can expand into expensive filters, and headers can carry untrusted identifiers, dates or content-negotiation values.

Input locationExampleValidation focus
Path/users/{user_id}Expected identifier grammar and length; authorization after lookup.
Query?limit=50&sort=-created_atType, bounds, field/operator allowlist.
HeaderIdempotency-KeyLength, syntax, uniqueness scope; never authorization by itself.
BodyJSON / multipartContent type, parser safety, schema, size and business constraints.

Normalize only where the contract calls for it. Security-sensitive identifiers should not silently change meaning because middleware lowercases, trims or decodes them differently from the authorization layer.

Using OpenAPI and JSON Schema Without Creating False Confidence

OpenAPI can describe request shapes and drive generated validation, while modern OpenAPI versions use JSON Schema concepts extensively. This is valuable for keeping documentation and implementation aligned, but generated validation is only as strong as the schema.

  • Mark required properties explicitly rather than relying on framework defaults.
  • Set numeric and string bounds that reflect actual business limits.
  • Model writable request fields separately from read-only response fields.
  • Test how the framework handles unknown properties and type coercion.
  • Keep authorization and domain validation after schema validation; neither can be inferred from a successful schema check.

For background on the specification itself, see Ammune’s OpenAPI schema and specification guide.

How Ammune Fits

Strong validation prevents malformed and unexpected inputs from entering application logic. Runtime API protection adds another layer by identifying repeated validation failures, unusual parameter behavior, automated probing and abuse patterns that may use individually valid requests. Ammune complements—not replaces—the server-side schema and authorization model.

Production Implementation Checklist

  • Enforce request/body size before expensive parsing.
  • Require supported Content-Type for requests with bodies.
  • Use safe parsers and reject malformed syntax.
  • Validate path, query, header and body inputs.
  • Define required fields, types, ranges, lengths and formats.
  • Decide explicitly whether unknown properties are rejected.
  • Use parameterized database access after validation.
  • Apply business rules and authorization as separate layers.
  • Return consistent machine-readable validation errors.
  • Monitor repeated validation failures and fuzz/probe behavior.

Frequently Asked Questions

What should a REST API validate?

Validate method and content type, request size, parsing, required fields, types, lengths, ranges, formats, allowed values, business constraints and authorization. Do not rely on frontend validation.

Should I use JSON Schema for REST API validation?

JSON Schema is a strong option for JSON request structure and constraints. It does not replace business rules or authorization, but it can make the public contract precise and reusable.

Should invalid API input return 400 or 422?

Both are used. 400 is appropriate for malformed requests; 422 Unprocessable Content is useful for syntactically valid representations that fail semantic or validation rules. Choose and document a consistent contract.

Should an API reject unknown JSON fields?

Strict APIs often reject them to catch mistakes and prevent unintended property binding. Some APIs intentionally ignore unknown fields for compatibility. The choice should be explicit, documented and safe.

Does input validation prevent SQL injection?

Not by itself. Validation reduces unexpected input, but database access should still use parameterized queries or safe ORM binding. Never concatenate untrusted values into SQL.

Primary References

Turn Validation Failures into Runtime Security Context

Validate every request in the application, then use runtime API visibility to identify repeated probing, abnormal inputs and automated abuse across endpoints.

© Ammune.ai — API security guidance for modern application environments.