400 vs 422 for validation errors: which one, and how to mock both

Your form submits, the API says no, and the frontend shows "Something went wrong". Half of the time the problem is not the error itself but which error it is: the client treats every 4xx the same, so a user who typed a quantity of 50 gets the same useless toast as a request your code built wrong. This guide explains when an API should answer 400 Bad Request and when 422 Unprocessable Content, why real APIs disagree, and how to mock both on a single endpoint so your client is tested against each one before the backend exists.

What the spec says

Both codes are defined in RFC 9110, the document that describes HTTP semantics today:

  • 400 Bad Request: the server cannot or will not process the request because of something perceived as a client error, for example malformed request syntax.
  • 422 Unprocessable Content: the server understands the content type and the syntax of the request is correct, but it is unable to process the instructions it contains.

The practical reading: 400 is "I can't read this" and 422 is "I read it, and no". 422 was born in WebDAV (as Unprocessable Entity), which is why older advice says not to use it in a plain REST API. Since RFC 9110 it is part of core HTTP, so that objection is gone.

A rule of thumb that holds up

The request…StatusWho can fix it
Is not valid JSON, or has the wrong Content-Type400The developer
Misses a required field400The developer
Sends a value of the wrong type ("quantity": "two")400The developer
Is well formed, but a value breaks a business rule (quantity above the limit)422The user
Is well formed, but conflicts with data the user can change (expired coupon, email taken)422The user

The last column is the useful one. A 400 means the client built a request it should never build: a bug. A 422 means a person typed or chose something the backend won't accept: feedback that belongs next to a field. Some teams use 409 Conflict for the "email already taken" case; that is fine too, as long as it is written down.

Why real APIs disagree

You will meet both conventions in the wild, often in the same project because the frontend talks to more than one backend:

  • GitHub's REST API answers 422 with "Validation Failed" and an errors array when a payload is rejected.
  • Stripe answers 400 for invalid or missing parameters, and puts the offending parameter in the error object.
  • FastAPI answers 422 for every request validation error by default, even for a missing field or a wrong type that the table above would call a 400.
  • Rails scaffolds answer 422 when a model fails its validations.

So the honest answer to "400 or 422?" is: follow the table if you design the API, and if you consume one, read its docs and test what it actually returns. Your client must survive both, and that is where a mock helps.

The client side: treat them differently

Start with a small error type that keeps the status and the parsed body, so the calling code can decide what to do:

export class ApiError extends Error {
  constructor(status, body) {
    super(body?.title || `Request failed with ${status}`)
    this.status = status
    this.body = body
  }
}

export const postJson = async (url, data) => {
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  })
  const body = await response.json().catch(() => null)
  if (!response.ok) throw new ApiError(response.status, body)
  return body
}

Then, in the form, map a 422 onto the fields and treat a 400 as what it is:

const onSubmit = async values => {
  try {
    const order = await postJson(`${API_URL}/orders`, values)
    navigate(`/orders/${order.id}`)
  } catch (error) {
    if (error.status === 422) {
      // The user can fix it: keep the values, highlight the fields
      setFieldErrors(Object.fromEntries(error.body.errors.map(e => [e.field, e.message])))
      return
    }
    if (error.status === 400) {
      // Our client sent something invalid: report it, don't blame the user
      reportBug('Order request rejected as malformed', { body: error.body })
      setFormError('We could not send your order. Please try again later.')
      return
    }
    throw error
  }
}

If you consume an API that uses 422 for everything, like a default FastAPI app, the same code still works: the field errors land on the form. If it uses 400 for everything, like Stripe, look at the body instead of the status to decide whether there is a field to highlight. Either way, the branches only stay correct if something exercises them, and waiting for the real backend to fail on cue is not a plan.

Mock both on one endpoint

In Mockfly an endpoint can have several responses, each with its own status code, and rules that pick one based on the request. Rules can read the body, a header, the query string, a URL parameter or a JSONPath expression, so the mock can reject a request the way a real validator would. Take POST /orders with three responses:

  1. Order created, 201, the default response.
  2. Business rule broken, 422.
  3. Malformed request, 400.

Create each extra response with the + button next to the status code, then add its rule from the Rules tab.

The Mockfly create rule modal with a rule that reads a property from the request body

The 400: missing or mistyped fields

On the Malformed request response, create a rule with the Match toggle set to any (OR) and two conditions:

  • Source Body, property productId, comparator notExists (no value).
  • Source Body, property quantity, comparator regex, value [^0-9], which matches a quantity such as "two" or -1.

Give it a body that says what is wrong, in the shape your real API uses:

{
  "title": "Bad request",
  "status": 400,
  "detail": "productId is required and quantity must be a positive integer"
}

The 422: well formed, but not acceptable

On the Business rule broken response, create a rule with Match any and:

  • Source Body, property quantity, comparator greaterThan, value 10.
  • Source Body, property coupon, comparator equal, value EXPIRED10.

The body can echo what the user sent with body substitution, so the message is specific:

{
  "title": "Validation failed",
  "status": 422,
  "errors": [
    { "field": "quantity", "message": "You can order up to 10 units, not {{body.quantity}}" }
  ]
}

One body for two conditions is a simplification: a single response always says the same thing. If you need a different message per field, split it into two 422 responses, one rule each.

Order matters when both match

What about { "quantity": "fifty", "coupon": "EXPIRED10" }? It is malformed and it has an expired coupon, so both rules match. Mockfly evaluates the rules of every enabled response, and when several match, the last one of the list is served. Keep the 400 below the 422 and the malformed request wins, which is what a real API does: it can't apply business rules to a payload it couldn't parse. The numeric comparators help too: greaterThan does not match a non-numeric value, so "fifty" never triggers the 422 on its own.

If you are not sure which response wins for a given request, the Flow tab draws the decision path of the endpoint, and this guide walks through reading it.

Try it from the terminal

MOCK=https://api.mockfly.dev/mocks/<your-project-slug>

# 201: valid order
curl -i -X POST $MOCK/orders -H "Content-Type: application/json" \
  -d '{ "productId": "p_42", "quantity": 2 }'

# 422: well formed, but above the limit
curl -i -X POST $MOCK/orders -H "Content-Type: application/json" \
  -d '{ "productId": "p_42", "quantity": 50 }'

# 400: required field missing
curl -i -X POST $MOCK/orders -H "Content-Type: application/json" \
  -d '{ "quantity": 2 }'

Lock the behaviour in with tests

Because the mock decides from the body, a test only has to send the right payload. No stubs in the test file, and the same scenarios are there for whoever opens the app against the mock:

import { describe, expect, it } from 'vitest'
import { postJson } from './api'

const API_URL = process.env.MOCK_API_URL

const expectStatus = async (data, status) => {
  const error = await postJson(`${API_URL}/orders`, data).catch(e => e)
  expect(error.status).toBe(status)
  return error
}

describe('POST /orders validation', () => {
  it('returns field errors for a business rule (422)', async () => {
    const error = await expectStatus({ productId: 'p_42', quantity: 50 }, 422)
    expect(error.body.errors[0].field).toBe('quantity')
  })

  it('rejects a request without productId (400)', async () => {
    await expectStatus({ quantity: 2 }, 400)
  })

  it('prefers 400 when the payload is malformed and breaks a rule', async () => {
    await expectStatus({ productId: 'p_42', quantity: 'fifty', coupon: 'EXPIRED10' }, 400)
  })
})

To run them without network, in CI or on a plane, pull the project with the offline CLI and serve it locally; it uses the same response engine, rules included:

npx mockfly-cli login
npx mockfly-cli pull
npx mockfly-cli serve   # http://localhost:4000/<project-alias>

MOCK_API_URL=http://localhost:4000/<project-alias> npx vitest run

Checklist

  • Your API docs say which errors are 400 and which are 422, and the backend follows them.
  • The client never shows a raw 400 next to a field; it logs it as a bug.
  • 422 errors keep the form values and land on the fields that caused them.
  • The mock has one response per error code, with rules that read the body.
  • The 400 sits below the 422 in the response list, so a malformed payload always wins.
  • A test sends each payload and asserts the status, against the hosted mock or the CLI.

For the other errors a client has to survive, 401, 404, 429, 500, slow responses and timeouts, see simulating API errors and edge cases.

Create a mock API with validation errors

Frequently asked questions

Should a validation error be a 400 or a 422?

Use 400 when the request itself is broken: invalid JSON, a missing required field, a value of the wrong type. Use 422 when the request is well formed but breaks a rule of your domain: a quantity above the limit, an expired coupon, an email that is already taken. Whatever you pick, document it and be consistent.

Is 422 only for WebDAV?

Not anymore. 422 was first defined for WebDAV, but RFC 9110 moved it into the core HTTP semantics in 2022 under the name Unprocessable Content, so any HTTP API can use it.

Why does my client need to tell 400 and 422 apart?

Because they mean different things to the user. A 422 is something the user can fix, so the form should keep its values and highlight the fields. A 400 usually means your own client sent something it should never send, so it is a bug to log, not a message to show next to a field.

How do I return a 400 and a 422 from the same mock endpoint?

Give the endpoint one response per status code and a rule on each one that reads the request body: for example notExists on a required field for the 400, and greaterThan on a numeric field for the 422. The default response answers when no rule matches, and when several match, the last response of the list wins.

Can the mock echo the invalid value in the error message?

Yes. Body substitution replaces {{body.field}} in the response with the value sent in the request, so the error can say exactly which value was rejected.