Aaron Aaron - 12 days ago 7
JSON Question

Micropost API format

I have been following this tutorial:https://www.railstutorial.org/book/user_microposts. My question is, how would I turn my microposts into a readable json format for my API? Here is my Micropost controller:

class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]

def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
render 'static_pages/home'
end
end

def destroy
end

private

def micropost_params
params.require(:micropost).permit(:content)
end
end


The only field for the micropost is the content field. How would I show this as json in my api? Also here is my Users controller that handles showing the micropost:

class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
end

def new
@user = User.new
end

def create
@user = User.new(user_params)
if @user.save
log_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end

private

def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end


I understand I need to create the api and version folders, but I do not know how I would format the micropost response into json. I was able to do it for my users, but I am struggling with the microposts. Help would be greatly appreciated :)

Answer

In order to respond with JSON, you might need to configure your controllers to respond to this format. One way to do it is by calling respond_to:

respond_to do |format|
  format.html
  format.json
end

Checkout Rails documentation for more details: http://api.rubyonrails.org/classes/ActionController/MimeResponds.html