What Is REST?
Read this post https://www.codecademy.com/article/what-is-rest
Init Rails API Only Project
rails new ideas-api --api --database=postgresql
Handle Cross-Origin Resource Sharing (CORS)
Rails use rack-cors
to avoid CORS issues when API is called from the frontend app (Read more: https://github.com/cyu/rack-cors).
Add the following line to Gemfile
, then run bundle install
:
gem 'rack-cors'
Insert rack CORS middleware to rails app. Create a file config/initializers/cors.rb
with following content:
Create Idea Resource
Generate Idea
model with these attributes: id, title, description, created_at, updated_at
.
rails g model Idea title:string description:textrails db:migrate
Add validations for Idea
model, modify file app/models/idea.rb
with following content:
Let's add some sample data, modify file db/seed.rb
with below code then run rails db:seed
(Note: I use faker
gem to generate dummy text):
Build Idea APIs
Config api routes, modify file config/routes.rb
with following code:
Define Idea
controller, create files app/controllers/api/v1/base_controller.rb
, app/controllers/api/v1/ideas_controller.rb
with following code:
After this step, it's done for super basic REST API, you can boot up your server rails s
and start to test your apis (I suggest to use Postman app).
Using JSONAPI Serializer To Render JSON
Sometimes you want more control in what be in JSON response. This might be required for:
- Adding some custom (virtual) attributes to resource
- Generating relationships between resources
- Having standard formats like JSONAPI
It’s time for jsonapi-serializer, jsonapi.rb gems.
Add the following line to Gemfile
, then run bundle install
:
gem 'jsonapi-serializer'gem 'jsonapi.rb'
Install jsonapi.rb
for rails app, create a file config/initializers/jsonapi.rb
with following lines:
Define IdealSerializer
by creating new files app/serializers/base_serializer.rb
, app/serializers/idea_serializer.rb
with following code:
To apply serializer to json response, modify file app/controllers/api/v1/ideas_controller.rb
like below:
Paginate Resource List Whenever You Can
I strongly recommend you use pagy
gem to handle pagination. It has great performance, you can visit https://github.com/ddnexus/pagy to see performance comparison with other gems.
Add the following line to Gemfile
, then run bundle install
:
gem 'pagy'
Config your pagy, create a file config/initializers/pagy.rb
with following code:
Include Pagy::Backend
to Api::V1::BaseController
and add page_number
, page_size
methods to get pagination params.
Modify index
method in app/controllers/api/v1/ideas_controller.rb
:
Restart rails server and test your apis again.
You can clone final source code of part 1 from here https://gitlab.com/tranquangvu/ideas-api/-/tree/part-1
Done!