52

When I

  render json: {
    error: "No such user; check the submitted email address",
    status: 400
  }

and then do my tests and check for

response.code

I get 200 rather than 400

I'm sure the answer to this absurdly simple, but I've been looking for an hour and cannot seem to get this working. I could just parse the Json and then check the status code...but isn't there a way to get response.code to return the status? I understand that technically it was a success and I assume that's why the response.code is returning 200, but I was using Jbuilder before where I could directly impact the code returned.

Morgan
  • 1,438
  • 3
  • 17
  • 32

1 Answers1

107

You have created the json there, which will be returned, and in that json will be an identification of the status - 400. However, that's not telling Rails to send the 400 status in the header.

You could do:

render json: {
  error: "No such user; check the submitted email address",
  status: 400
}, status: 400

Or something like

payload = {
  error: "No such user; check the submitted email address",
  status: 400
}
render :json => payload, :status => :bad_request

You can use either the symbol :bad_request or the status number 400.

Richard Jordan
  • 8,066
  • 3
  • 39
  • 45
  • Ugh. Thanks so much. I must've typed code: 400 when I saw that before. – Morgan Feb 20 '14 at 02:04
  • and the inner status isn't necessary either; sweet. – Morgan Feb 20 '14 at 02:07
  • 2
    Great. I didn't think the status key/value in the json was what you were looking for, but I included it in the example just in case. – Richard Jordan Feb 20 '14 at 02:15
  • 1
    is there a reason I'd want the json to have the identification of the status rather than just have it in the header? Thanks again for your help! – Morgan Feb 20 '14 at 02:16
  • 3
    So I've seen all kinds of json response payloads including error information, status information and the like. Perhaps the client finds it easier to process the json response than the header information for one reason or another. Lots of public APIs do this. A great resource for building APIs, with good ideas about response payloads (that I refer to regularly) is Brian Mulloy's 'RESTful API design' slide deck: http://www.slideshare.net/apigee/restful-api-design-second-edition – Richard Jordan Feb 20 '14 at 02:23
  • 2
    FYI, there's a newer edition of the API Design slides: http://www.slideshare.net/apigee/api-design-3rd-edition – Dennis Nov 05 '14 at 16:51
  • 3
    This is a handy link. http://billpatrianakos.me/blog/2013/10/13/list-of-rails-status-code-symbols/ – Volte Sep 28 '15 at 21:05