Write APIs the Same Way We Write Other Code
Let’s learn the way of writing the APIs the same way as we write our other codes.
We'll cover the following...
Ideally, a controller that powers an API should look just as plain as any other controller:
Press + to interact
class WidgetsController < ApplicationControllerdef indexwidgets = Widget.allrender json: { widgets: widgets }enddef createwidget = Widget.create(widget_params)if widget.valid?render json: { widget: widget }, status: 201elserender json: { errors: widget.errors }, status: 422endendend
We may not want exactly this sort of error handling, but we get the idea. There’s rarely a reason to do anything different in our API controller methods than in our non-API methods.
We would be well-served to do a couple of things before writing any API code, and that’s to create a separate routing ...