Secure API input validation starts before business logic runs. This checklist explains how to define request schemas, normalize values safely, reject ambiguous input, handle nested and cross-field rules, and return useful errors without exposing sensitive implementation details.
Overview
API input validation is the process of checking that a request is structurally correct, within defined limits, and appropriate for the operation being requested. It is not a replacement for authorization, database constraints, output encoding, or fraud controls. Instead, it creates a controlled boundary between external input and application logic.
A reliable validation design usually has four layers:
- Transport checks: Confirm the HTTP method, content type, request size, character encoding, and authentication context expected by the endpoint.
- Schema checks: Validate field names, data types, required properties, nullability, formats, lengths, ranges, and array limits.
- Business-rule checks: Compare related fields and confirm that the requested state change is allowed for the current resource and user.
- Security and operational checks: Limit resource consumption, prevent unsafe interpretation of input, create appropriate audit records, and return consistent errors.
Keep these layers distinct in code and documentation. A syntactically valid request may still fail a business rule, and a request that passes both may still require a risk decision or manual review. For APIs that process payments, identity data, or verification evidence, pair schema validation with controls for replay, idempotency, auditability, and privacy. See the payment webhook replay and idempotency checklist and the validation audit trail guide for related workflows.
Checklist by scenario
1. Define the request contract
Start with an explicit contract for every endpoint. Document the accepted media type, required fields, optional fields, nullable fields, defaults, formats, and response behavior. Use a machine-readable schema where practical, but do not assume that publishing an OpenAPI document automatically enforces it at runtime.
- Choose types deliberately: string, integer, number, boolean, array, or object.
- Set minimum and maximum lengths for strings and limits for arrays and nested objects.
- Define numeric ranges and whether decimals, negative values, or exponential notation are accepted.
- Specify whether omitted and explicitly null values have different meanings.
- Decide whether unknown fields are rejected, ignored, or preserved. Rejecting them is often clearer for strict commands; controlled tolerance may be useful for forward-compatible integrations.
- Set a maximum body size before parsing large or deeply nested content.
For a broader approach to schema ownership, versioning, and compatibility testing, use the API contract validation playbook.
2. Normalize without changing meaning
Normalization should make equivalent representations consistent, not silently rewrite user intent. Decide which transformations are permitted for each field and apply them before comparisons or persistence.
- Trim surrounding whitespace where it cannot be meaningful.
- Normalize case only for case-insensitive identifiers, such as a field whose contract explicitly treats values as case-insensitive.
- Use a documented Unicode normalization strategy when names, addresses, or other international text are accepted.
- Parse dates with an explicit format and timezone rule rather than relying on a language runtime's permissive parser.
- Convert phone numbers, email addresses, domain names, and identifiers according to their own field rules instead of applying one global transformation.
- Preserve the original value when it is needed for display, evidence, or audit purposes, while storing a separate canonical form for matching.
Canonicalization is not a substitute for authorization. A normalized identifier must still be checked against the authenticated user's permissions and the intended resource.
3. Validate nested objects and collections
Apply limits at every level, not only to the top-level request. A valid outer object can contain an excessive number of children, deeply nested structures, or repeated values that create processing and storage problems.
- Set maximum nesting depth where the format or parser permits it.
- Limit array length and validate each item against an item schema.
- Define whether duplicate items are allowed and how duplicates are compared.
- Require stable identifiers for updates rather than trusting array position.
- Prevent mutually exclusive properties from appearing together.
- Reject unexpected object shapes when downstream code assumes a fixed structure.
4. Apply cross-field and state rules
Field-level checks cannot answer questions that depend on relationships. Add explicit rules for combinations such as start and end dates, currency and amount, delivery method and address, or verification status and requested action.
- Require an end date to be present when a recurring schedule is selected.
- Ensure a lower bound does not exceed an upper bound.
- Require a confirmation field to match its source value without logging either value unnecessarily.
- Check that a referenced resource exists and belongs to the caller's permitted scope.
- Verify that a state transition is valid for the current server-side state, not merely the state supplied by the client.
5. Add field-specific security controls
Use allowlists and purpose-specific parsers wherever possible. Validation should reduce ambiguity before input reaches database queries, template rendering, shell commands, file handling, or external services. Parameterized queries, output encoding, safe file APIs, and command restrictions remain necessary; a regular expression alone is not an injection defense.
For webhook and callback endpoints, validate the envelope, signature, timestamp or replay controls where applicable, event type, and payload schema. For identity or document workflows, separate format validation from authenticity signals and review decisions. Related guidance is available in the document verification API integration guide.
6. Return safe, actionable errors
Use one stable error envelope across endpoints. A useful response can include an application error code, a general message, and field-level locations such as customer.email or items[2].quantity. Avoid returning stack traces, SQL fragments, parser internals, secret values, complete identity documents, or sensitive request content.
Distinguish client-correctable validation failures from authentication, authorization, rate-limit, conflict, and server errors. Keep the external message understandable while recording more diagnostic detail in protected internal logs. Do not let clients infer confidential resource existence through overly specific errors.
What to double-check
| Area | Questions to answer |
|---|---|
| Types and formats | Are dates, decimals, identifiers, URLs, and encoded values parsed explicitly? |
| Required and nullable | Does omission differ from null, empty string, zero, or false? |
| Length and size | Are limits defined for the body, strings, arrays, files, and nested depth? |
| Unknown fields | Are extra properties rejected or handled deliberately for compatibility? |
| Canonicalization | Could trimming, case conversion, or Unicode handling change identity or evidence? |
| Authorization | Is access checked against server-side identity and resource state? |
| Errors | Are responses consistent, actionable, and free of sensitive implementation details? |
| Observability | Can the team trace a validation decision without storing unnecessary personal data? |
Test each rule with valid, invalid, boundary, missing, null, duplicated, unexpectedly encoded, and excessively large values. Add contract tests for important clients and negative tests for security-sensitive fields. If an endpoint accepts email, domain, or authentication-related data, keep its validation rules separate from domain-specific checks such as MX, SPF, DKIM, or certificate validation. A schema can confirm that a value is shaped like a domain; it cannot by itself establish that the domain is configured correctly. The DNS and SSL validation checklist covers those separate checks.
Common mistakes
- Validating only in the client: Browser and mobile checks improve usability but cannot protect an API. Repeat authoritative validation on the server.
- Using one permissive parser for every field: General-purpose date, URL, and number parsers may accept representations the contract never intended.
- Treating validation as authorization: A well-formed resource ID is not proof that the caller may read or modify it.
- Over-normalizing identifiers: Converting case or punctuation without a field-specific rule can merge distinct values or damage evidence.
- Returning all internal detail: Verbose parser errors can expose schemas, database behavior, or sensitive input.
- Ignoring unknown fields silently: This can hide client bugs, miss attempted parameter injection, and make contract changes difficult to detect.
- Logging complete failed requests: Validation failures may contain passwords, tokens, identity data, or payment information. Log the minimum needed for diagnosis and audit.
- Skipping resource and cost limits: A structurally valid request can still trigger excessive computation, storage, recursion, or calls to downstream services.
When to revisit
Review an API validation policy before adding an endpoint, changing a request or response contract, introducing a new client, or accepting a new media type. Revisit it before seasonal planning cycles when traffic patterns, batch sizes, or operational limits may change, and after penetration tests, incidents, dependency upgrades, or changes to framework schema behavior.
Use this short maintenance routine:
- Compare the published contract with runtime behavior and client assumptions.
- Review rejected requests for recurring confusion, unsafe probing, or missing business rules.
- Recheck parser, schema-library, gateway, and framework changes before deployment.
- Run boundary, negative, authorization, and sensitive-data logging tests.
- Confirm that error codes, documentation, dashboards, and runbooks still agree.
- Record the validation-policy owner, review date, and next trigger.
Consistent API input validation is a living control, not a single middleware setting. Treat schemas, normalization rules, authorization checks, limits, and error formats as part of the service contract, then update them whenever workflows or tools change.