DEV Community

Cover image for Turning your Rails App into an API
Rixio Barrios
Rixio Barrios

Posted on

Turning your Rails App into an API

When you generate a scaffold in Rails you'll get the method
respond_to, this method would let you render data in other formats including JSON. To service the same data you are rendering on HTML as an end-point, you could make the following change under your controller using your own variables:

def index
# Using an @task model
respond_to do |format|
  format.json do
    render json: @task
  end
end
Enter fullscreen mode Exit fullscreen mode

Alternatively, you could do this to render more formats and also use a shorter syntax:

def index
  @tasks = Task.all
  respond_to :html, :json, :xml
end

Enter fullscreen mode Exit fullscreen mode

Top comments (0)