Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
As we've been doing through and implementing our API responses, we've introduced a common but subtle mistake in how we send back status codes. In this video, we're going to fix it.
Code Samples
Here is a small snippet in our create method:
def create
list = TodoList.new(list_params)
if list.save
render json: {
status: 200,
message: "Successfully created todo list.",
todo_list: list
}.to_json
end
end
We fix it to properly return the correct status code by moving the status key to be an argument to the render method rather than a hash key in the json argument:
render status: 200, json: {
message: "Successfully created todo list.",
todo_list: list
}.to_json
We then apply this to the rest of the controller actions.
Useful Links
-
0:00
As we've been going along coding our API responses,
-
0:03
we've accidentally introduced one of the most common errors when creating an API.
-
0:07
If we look at our code for each of the responses, we're returning a JSON object
-
0:11
with a status key and the corresponding HTTP status code that we want.
-
0:16
While it isn't necessarily a problem to send along a status code
-
0:19
as part of our API, let's take a look at the response.
-
0:24
Notice the very first line.
-
0:27
The HTTP response is a 200 OK status when in fact we wanted it to have a 500 status.
-
0:34
Luckily, this is an easy fix.
-
0:37
We'll move the status key out of the response object.
-
0:41
[BLANK_AUDIO]
-
0:44
And instead, put it as a argument to the render method.
-
0:49
Now if we redo the cURL request, we get the proper response.
-
0:54
Well, it's almost the proper response.
-
0:56
A 500 error means that the server had some kind of internal error.
-
1:00
However, the server, our Rails app, is just fine.
-
1:04
It's actually the data that isn't correct for what we're doing.
-
1:08
If we look at the HTTP standards, it looks like the status code,
-
1:13
422, Unprocessable Entity, is more appropriate and
-
1:17
is also the status most preferred by Rails.
-
1:20
Other acceptable codes would be 406, which stands for Not Acceptable, and 403,
-
1:25
Forbidden, which says that the server understood the request but
-
1:28
is refusing to fulfill it.
-
1:31
There's some debate over whether or not 400 Bad Request is acceptable, and
-
1:35
it's up to you which you choose for your API.
-
1:38
We're going to use 422, Unprocessable Entity, for ours.
-
1:43
Now when we perform the cURL request again, we get the correct status code.
-
1:51
One last thing, we'll go back and fix this for the successful status code as well.
-
1:57
Now we just have to go back and fix the rest of our methods.
-
2:00
[BLANK_AUDIO]
-
2:05
Now I've gone through and fixed all of the status codes.
-
2:09
Now your code should look something like this.
-
2:13
Perfect
You need to sign up for Treehouse in order to download course files.
Sign up