We have summarized the steps to create an API using Rails' API mode.
$ rails new api-task --api
You can create an app in API mode by adding --api to the end of the normal rails new command. (By default, parts not needed for the API will not be created.)
Create a model and controller just like a regular Rails app.
rails g model category name:string
rails g model idea category_id:bigint body:text
$ rails db:create
$ rake db:migrate
By creating a namespace with the version as shown below from the beginning, future API version control will be easier.
config/routes.rb
Rails.application.routes.draw do
namespace 'api' do
namespace 'v1' do
resources :posts
end
end
end
The directory structure is as follows according to the namespace set in the root.
---- controllers
--- api
-- v1
- ideas_controller.rb
- categories_controller.rb
class IdeasController < ApplicationController
def index
@ideas = Idea.all
render json: @ideas
end
def create
@idea = Idea.new(idea_params)
if @idea.save
render json: @idea, status: :created, location: @idea
else
render json: @idea.errors, status: :unprocessable_entity
end
end
private
def idea_params
params.require(:idea).permit(:catagory_id,:body)
end
end
class CategoriesController < ApplicationController
def index
end
def create
@category = Category.new(idea_params)
if @category.save
render json: @category, status: :created, location: @category
else
render json: @category.errors, status: :unprocessable_entity
end
end
private
def category_params
params.require(:category).permit(:name)
end
end
Create some ideas and check with a browser Get(http://localhost:3000/api/v1/ideas)
If it is displayed as above, it's OK! !!
Recommended Posts