This content originally appeared on DEV Community and was authored by April Skrine
Let's talk through some basics to building out an API in Rails.
This assumes you already have a rails directory started. If not, run rails new [name] --api
to start new. Make sure you have rails installed first by running gem install rails
!
1. Build out your resources
For the sake of this example, we're going to work with the following:
- Owner --< Pets >-- Pet Sitters
- An owner can have many pets
- A pet sitter has many pets they take care of
Let's build out our resources. We're going to use rails g resource
because it will generate model, controller, migration and serializers for us.
rails g resource owner name phone:integer
rails g resource sitter name phone:integer active:boolean
rails g resource pet name age:integer sitter:references owner:references
This will build out our resources, and include the foreign keys in the pet migration.
2. Add/confirm relationships
Let's make sure our relationships are correct. The resource generator automatically generated the belongs_to
when we used references, but we need to go into the Owner and Sitter models and include:
In Owner:
has_many :pets
has_many :sitters, through: :pets
In Sitter:
has_many :pets
has_many :owners, through: :pets
Now our relationships are confirmed. In the Pets model you should see:
belongs_to :owner
belongs_to :sitter
This is also a good time to think about whether any relationships will need dependent: :destroy but more on that later.
3. Validations
Now that our models are linked, let's look at validations in our models. Let's assume an owner must be 16 or older to use the service, and a pet sitter must be 18 to be a pet sitter. Also, a pet cannot be created without a name.
In Owner model:
validates :age, numericality: {greater_than_or_equal_to: 16}
In Sitter model:
validates :age, numericality: {greater_than_or_equal_to: 18}
In Pet model:
validates :name, presence: true
4. Routes
Let's take a look at our routes in Config >> Routes. Since we used the resource generator, we'll see:
resources :owners
resources :sitters
resources :pets
This means that all default routes are currently open. Let's clean up what's accessible:
resources :owners, only: [:index, :show, :create, :destroy]
resources :sitters, only: [:index, :show, :create, :destroy]
resources :pets, only: [:index, :show]
We can define the routes any way we want to, but this is what we'll use for now.
5. Controllers
Now that we've got the routes defined, let's head for the Controllers and get some of the routes defined. Let's just look at an example of OwnersController:
def index
owners = Owner.all
render json: owners, status: :ok
end
def show
owner = Owner.find(params[:id])
render json: owner, status: :found
end
def create
render json: Owner.create!(owner_params), status: :created
end
def destroy
Owner.find(params[:id].destroy
head :no_content
end
private
def owner_params
params.permit(:name, :phone)
end
Make sure each Controller has routes defined for each route we've specified in our Config >> Routes. Technically we didn't really need strong params for this, but I wanted to show an example.
6. Serializers
Ensure that the serializer gem is in the Gemfile. If it's not, add gem "active_model_serializers", "~> 0.10.12"
Our resource generator generated serializers for each model already. We can use those to limit what we receive in our responses. Anything in the related Controller will default to the serializer with the matching name, unless you specify otherwise. In our OwnerController, that would look like:
render json: <something>, serializer: <CustomSerializerName>
This content originally appeared on DEV Community and was authored by April Skrine
April Skrine | Sciencx (2022-03-18T18:17:34+00:00) Simple, beginner steps: API with Rails!. Retrieved from https://www.scien.cx/2022/03/18/simple-beginner-steps-api-with-rails/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.