API Security

Create Stable JSON Request and Response Contracts

Define predictable JSON shapes, validation behavior and field evolution rules so API clients can integrate without guessing.

A JSON API contract describes more than the names of fields. It defines required and optional values, types, null behavior, date formats, identifier formats, error structures and how the representation may evolve. If one endpoint returns id as an integer and another returns it as a string, client code becomes unnecessarily complicated. Establish conventions before multiple consumers depend on them.

Define representation rules

Choose a consistent media type, character encoding and date-time format. ISO 8601 timestamps with an explicit timezone are easier to interpret than server-local date strings. Distinguish an omitted field from a field explicitly set to null: omission can mean “not included,” while null can mean “known to have no value.” Document numeric precision and avoid floating-point values for money; use integer minor units or decimal strings with a defined currency.

Validate input separately from output

Never return an entire database row as an API response. Map allowed request fields into application commands and map domain data into an explicit response representation. This prevents internal columns, password hashes, moderation flags or private notes from leaking when the schema changes. Reject unknown or disallowed fields where appropriate, especially for sensitive updates.

Use a consistent error envelope

{
  "error": {
    "code": "validation_failed",
    "message": "The request contains invalid fields.",
    "fields": {"email": "Enter a valid email address."}
  }
}

Keep code stable for programmatic handling; human-readable messages can improve without becoming a machine contract. Do not expose exception messages or secrets.

Evolve carefully

Adding an optional response field is usually safer than changing an existing field's type or meaning. Treat removing fields, changing enum values and making optional input required as potentially breaking changes. Maintain example payloads and contract tests so changes are reviewed before release.

Further reading

Share this page Help other developers discover this resource.