Andrey Inishev Andrey Inishev - 3 days ago 7
JSON Question

Rails: validation error codes in JSON

So, I am writing Rails web application which has JSON API for mobile apps. For example, it sends POST JSON request to example.com/api/orders to create order.

{id: 1, order: { product_name: "Pizza", price: 10000}}


In case of validation errors I can response with HTTP 422 error code and order.errors.full_messages in json. But it seems better for me to have specific error code in JSON response. Unfortunately, it seems like Rails does not provide ability to set error code for validation error. How to solve this problem?

Answer

You can pass a custom status code by using the status option when rendering the response.

def create
  @order = ...

  if @order.save
    render json: @order
  else
    render json: { message: "Validation failed", errors: @order.errors }, status: 400
  end
end

I usually tend to return HTTP 400 on validation errors. The message is a readable status response, the errors are also attached.

This is a respons example

{
    message: "Validation failed",
    errors: [
        ...
    ]
}

You can also embed additional attributes.

Comments