Use the Simplest Content Type We Can

Learn the content type we should be using in the APIs.

We'll cover the following

The HTTP Accept header allows for a wide variety of configurations for how a client can tell the API what sort of content type it wants back (the Content-Type header is for the server to specify what it’s sending). We can ignore it altogether and always serve JSON, or we could require the content type to be application/json, create our own custom content type for all our resources, or even make a content type for each resource. The possibilities and associated carrying costs are endless.

We would not recommend ignoring the Accept header. It’s not unreasonable to ask clients to set it, it’s not hard for them to do so, and it allows us to serve other types of content than JSON from our API if we need it.

We would discourage you from using custom content types unless there is a very specific problem we have that it solves. When we discuss JSON serialization, we will recommend using to_json, and we will not recommend stuff like JSON Schema, as it is highly complex. Thus, a content type of application/json would be sufficient.

That said, if we decide we need to use more advanced tooling like JSON Schema, a custom content type could be beneficial, especially if we have sophisticated tooling to manage it. If we have to hand-enter a lot of custom types and write custom code to parse out the types, we are probably over-investing.

While we should examine the Accept header, there’s no reason to litter our API code with respond_to calls that will only ever respond to JSON. Thus, we can have a single check-in ApiController for the right content type. Rails provides the request method that encapsulates the current request. It has a method format that returns a representation of what was in the Accept header that can respond to json? to tell us if the request was a JSON request.

We can use this and, if the request is not JSON, return an HTTP 406 (which indicates that the app doesn’t support the requested format). First, we’ll specify a callback. We want it after the authentication callback because there’s no sense in checking the content of an unauthorized request.

Get hands-on with 1200+ tech skills courses.