HTTP 422 status code means the server understands the response body but couldn’t process the request because there’s something wrong with the content.
While the request body (payload) can be technically correct, it can fail in different ways:
- data that threatens the integrity of the entire dataset
- incorrectly formatted data
- non-existing fields
400 vs 422
If the client sends you a malformed or invalid JSON, you would return the
400 Bad Request. If the JSON itself is valid, but some fields aren’t, you should respond with
422 Unprocessable Entity.
Likewise, if the data client sends is valid but doesn’t pass server-specific validations, you should probably respond with 422.
For example, if you’re building an API for an e-commerce platform, 422 would be appropriate when the client:
- creates a product without a name
- Incorrectly formats the data
- checks out products that are out-of-stock
Rails responds with
422 Unprocessable Entity when the client fails to pass a CSRF check. There are two ways around this problem:
- Send CSRF tokens on all non-GET requests
Starting from version 5.2, Rails automatically enables CSRF checks in all views/controllers. If you’re sending AJAX requests, you have to explicitly include the
- Disable CSRF checks (not recommended)
You can disable the CSRF check for a particular (or all) controller by including the
class UsersController < ApplicationController skip_before_action :verify_authenticity_token end
Note that this opens your app for a CSRF attack. You should only do this if you trust the input (for example, webhooks from a third-party API).
No spyware, no promotional emails, or keyword-stuffed junk. I will only send you a single email when I've got something interesting to say. Unsubscribe anytime.
You can also subscribe to the Atom feed (it's like RSS, but better).