...

/

Write APIs the Same Way We Write Other Code

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 < ApplicationController
def index
widgets = Widget.all
render json: { widgets: widgets }
end
def create
widget = Widget.create(widget_params)
if widget.valid?
render json: { widget: widget }, status: 201
else
render json: { errors: widget.errors }, status: 422
end
end
end

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 ...