What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

API validation is the server-side process of checking that incoming requests have the expected structure, types, formats, limits, and business meaning before application code acts on them. It should happen as early as possible, at a trusted boundary, and in more than one layer: schema and syntax checks catch malformed data, while semantic and business-rule checks catch values that are well-formed but unacceptable in context.

Client-side validation can make forms easier to use, but it is not a security control. A caller can disable JavaScript, alter a request, or call your endpoint through a proxy. The server must repeat every security-relevant check.

What API validation checks

Validation answers two different questions. Syntax asks whether a value has the required shape. Semantics asks whether that value makes sense for this operation, account, and workflow. A string such as 2026-14-40 may resemble a date but is not a valid calendar date; a real date may still be outside the dates a booking endpoint permits.

Structure and types

Confirm that the request contains the fields the endpoint expects and that each field has the right type. Parse JSON with a strict parser, distinguish a number from a numeric-looking string, and represent booleans and dates with unambiguous types. Reject unknown or unexpected fields when your contract requires a closed object; otherwise decide explicitly how they are handled rather than silently trusting them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Formats

Structured values need a defined format: an ISO date, currency amount, UUID, email address, or domain-specific identifier. Use a narrowly defined pattern only when it describes the real format. A broad regular expression can accept invalid values, while an over-restrictive one can reject legitimate international text.

Length, range, and request size

Set maximum and minimum lengths for strings, bounds for numbers, and permitted date ranges. Apply an overall request-body limit as well. An oversized body should be rejected before expensive parsing or processing; HTTP 413 is the usual response for a payload that exceeds the documented limit.

Relationships and business meaning

Fields often constrain one another. An end date must follow a start date, a quantity must fit inventory, and a currency must be supported by the selected account. These are semantic rules, not merely type checks. Validate them after basic parsing and before invoking side effects such as charging a card or creating a shipment.

Headers and content type

Validate the message envelope as well as its body. Document accepted request media types, such as application/json, and reject an unexpected Content-Type with an appropriate error, commonly HTTP 415. Do not blindly reflect a caller’s Accept header as your response Content-Type; select a representation your service actually supports.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Where validation belongs

Put an early validation layer at the server or service boundary, before application functions process untrusted values. A gateway can enforce coarse limits and media types, while the service validates the complete schema and business rules. Validation at several layers is useful when each layer has a clear responsibility, but avoid contradictory rules that produce different answers for the same request.

Client checks improve usability

Browser and mobile clients can show immediate messages, prevent obvious typos, and reduce unnecessary requests. They are still advisory. Client-side JavaScript can be disabled or modified, and an attacker can send a request without using your interface.

Server checks provide the trust boundary

The server owns authorization and security decisions. Treat every query parameter, path parameter, header, body field, uploaded file, and nested object as untrusted until it has passed the checks required for that endpoint. Validate before database writes, template rendering, command execution, or calls to other services.

How to design a validation contract

  1. Define the accepted shape. List required and optional fields, their types, nullability, and whether unknown properties are allowed.
  2. Define formats and bounds. Specify date representation, identifier syntax, string lengths, numeric precision, and request-size limits.
  3. Define allowed values. For a small fixed set, use an allowlist such as "pending", "approved", and "rejected". A client dropdown is not proof that a submitted value is authorized.
  4. Define cross-field rules. State relationships such as end_at > start_at, mutually exclusive fields, and conditions that depend on account state.
  5. Define failure behavior. Choose stable status codes and a machine-readable error format without exposing stack traces, SQL, parser internals, or secrets.
  6. Version the contract deliberately. Adding an optional field is usually less disruptive than changing a type or removing a value. Keep compatibility rules explicit for each API version.

Schema validation and business rules

A JSON or XML schema is a strong first filter. It can enforce required properties, primitive types, enumerations, patterns, and numeric or string bounds. It cannot know every workflow rule. After schema validation, run contextual checks against current state and the authenticated principal.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, a schema can require two date strings and confirm their format. Service logic must still verify that the interval is ordered, falls within the product’s booking window, and does not overlap a prohibited reservation. Keep these stages separate so an error identifies whether the document is malformed or the requested operation is not allowed.

Centralize shared rules, preserve field-specific rules

Shared validators for UUIDs, pagination limits, timestamps, and common headers reduce drift. Do not force unrelated fields through one generic rule: a postal code, display name, and opaque token have different formats and threat models. Use maintained validation facilities for your language or framework, and test their edge cases, Unicode handling, and version behavior.

Validation is not the whole security model

Validation limits what enters a workflow; it does not make later uses safe. Use parameterized database queries rather than concatenating validated strings. Apply output encoding for the destination context, such as HTML, JavaScript, SQL, or a shell. Sanitize content when the product intentionally accepts a richer language such as HTML. Parse serialized data with safe, constrained settings.

Do not turn a denylist into your primary defense. Blocking a few attack-looking substrings can reject legitimate names and is easy to evade with alternate encodings. Prefer explicit accepted structures and values, then apply context-specific defenses at the point of use.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Message-level and parser protections

  • Set a maximum body size at the edge and in the application server.
  • Accept only documented media types and return 415 for unsupported request formats.
  • Use a secure JSON or XML parser. XML processing needs particular care around external entities and related parser attacks.
  • For uploads, inspect the actual file content and enforce size and format limits; do not trust the filename extension or client-provided MIME type.
  • For serialized objects, constrain permitted types and avoid unsafe deserialization.
  • Apply rate and concurrency controls separately from validation; a valid request can still be abusive.

OWASP’s REST guidance covers request-size limits, secure parsing, content types, and generic client-facing errors: OWASP REST Security Cheat Sheet.

Errors clients can act on

Use a stable envelope with an error code, a human-readable summary, and field-level details where disclosure is safe. Keep messages specific enough to fix the request but generic enough not to reveal implementation details. Never return call stacks, SQL statements, internal hostnames, or parser diagnostics to an untrusted caller.

A practical distinction is:

  • 400 Bad Request: the document cannot be parsed or violates a general request rule.
  • 413 Content Too Large: the body exceeds the published size limit.
  • 415 Unsupported Media Type: the request’s content type is not accepted.
  • 422 Unprocessable Content: syntax is understood but field or business validation fails, where your API uses this convention.
  • 401 or 403: authentication or authorization fails; do not substitute validation errors for access control.

Keep error codes stable even if prose changes. Log detailed diagnostics on the server with correlation identifiers, while returning only the minimum useful detail to the client.

A complete validation flow

  1. Terminate transport and authentication checks first, including limits that can be enforced before body parsing.
  2. Verify the request method, path parameters, content type, and body size.
  3. Parse with a safe parser and reject malformed syntax.
  4. Validate the schema: required fields, types, formats, lengths, ranges, and enumerations.
  5. Normalize only where the contract permits it, such as Unicode normalization for identifiers. Preserve user text when normalization would change its meaning.
  6. Evaluate cross-field and state-dependent business rules.
  7. Authorize the requested resource and operation for the authenticated principal.
  8. Only then perform side effects, using parameterized queries and context-aware output encoding.

Testing validation thoroughly

Unit-test each rule with valid boundary values, just-out-of-range values, missing fields, nulls, wrong types, duplicate properties, unexpected properties, and malformed encodings. Add integration tests that send the real HTTP envelope, including headers and body-size limits. Property-based or fuzz testing can expose parser and Unicode edge cases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test error stability as well as acceptance. A request rejected by the gateway should not be accepted by a downstream service, and a schema update should not silently widen an authorization rule. Include regression cases for every production incident, but do not record sensitive payloads in test fixtures.

Example: validating a screenshot request before capture

Suppose an internal endpoint accepts a target URL, an output format, and an optional viewport. A schema can require an absolute HTTPS URL, allow only png, jpeg, or webp, and bound viewport dimensions. Business logic can then apply the caller’s permitted domains and prevent requests to destinations your service must not access. Validation does not replace network egress controls, authentication, authorization, or defenses against server-side request forgery.

Rank #4
API Security in Action
  • API Security in Action
  • Manning Publications
  • ABIS BOOK

Before calling any external screenshot service, validate the URL with a real URL parser, enforce an allowlist appropriate to your product, cap user-controlled wait times and dimensions, and reject unexpected options. Log the normalized decision, not secrets such as API keys.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup: ScreenshotNeo

If your goal is simply to obtain a clean website image or PDF after validating the target URL, ScreenshotNeo provides a single HTTP endpoint. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and each response reports its page verdict and billing status in X-Page-Verdict and X-Billed headers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the documented options and parameter names in the ScreenshotNeo API documentation. The following calls are complete examples; replace the key and target URL with values that have passed your own validation.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, PDF paper and page controls, HTML/CSS rendering, custom CSS and JavaScript, pre-capture clicks, selector hiding, selector or network-idle waits, request and resource blocking, custom headers, cookies, user agents, Authorization, timezone and geolocation, transparent backgrounds, resizing, chosen-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

The Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is on every plan, and yearly billing gives two months free. Sign up free for ScreenshotNeo.

Troubleshooting validation failures

“Missing field” although the client sent it

Check the exact property name, casing, nesting, and content type. A form-encoded body is not equivalent to JSON, and an empty string is not the same as an omitted property unless your contract says so.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A number is rejected as a string

Decide whether coercion is part of the contract. If not, reject "10" where a JSON number is required. If coercion is allowed, parse strictly and test whitespace, exponent notation, precision, and overflow.

Valid-looking dates fail

Define timezone and precision rules. Parse with a date-time library rather than comparing strings unless the representation is canonical, and enforce business boundaries after parsing.

Large requests time out

Enforce a body limit before expensive processing, stream only where the parser and business logic support it, and return 413 for over-limit bodies. Do not raise limits merely to accommodate an unbounded client.

Different services disagree

Publish one contract, share schema artifacts where practical, and test the gateway, service, and client against the same examples. Record which layer generated each error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Performance, reliability, and operations

Cheap checks should run first: method, content type, size, and basic syntax before database lookups or remote calls. Bound regex execution, recursion depth, array lengths, and nested object depth to prevent pathological inputs. Cache immutable schema definitions, not decisions that depend on changing authorization or account state.

Observe rejection counts by endpoint and error code, latency spent parsing and validating, body-size distributions, and downstream failures after accepted requests. Alerts should distinguish a client deployment sending malformed data from an attack or a broken validator. Roll out stricter rules with a documented compatibility plan; changing a previously accepted value can break existing clients.

Frequently Asked Questions

Is validation the same as sanitization?

No. Validation decides whether input meets an allowed contract. Sanitization transforms data for a particular use, while output encoding protects a destination context. They solve different problems.

Can an API rely on JSON Schema alone?

No. A schema is useful for structure and declared constraints, but authorization, current-state checks, and cross-field business rules still require application logic.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should unknown JSON fields be rejected?

Choose deliberately. Rejecting them catches client mistakes and prevents accidental widening; accepting them can aid forward compatibility. Document the policy and apply it consistently.

What should be logged for a failed request?

Record an endpoint, stable error code, correlation identifier, and safe diagnostic context. Avoid logging credentials, tokens, full personal data, or sensitive request bodies.

Quick Recap

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.