012.Making api with grape (route)


Tiếp theo phần Grape cơ bản, post này nói về các khai báo route trong ruby grape.
Refactor lại route
Sau bài basic trước, các bro sẽ thắc mắc là nếu nhiều api hơn thì chúng ta làm thế nào. Tạo thêm nhiều hàm hơn trong file health_check.rb? Hay là tạo thêm nhiều file tương tự health_check.rb rồi add vào trong file routes.rb?
Cả 2 cách đều chạy được, nhưng ở đây, chúng ta không làm thế.
Với Rails, chúng ta sử dụng mount để tạo dựng route. Lấy hướng dẫn của tác giả thư viện làm mẫu, chúng ta sẽ khai báo tất cả các mount ở trong các file base.rb, sau đó base.rb ngoài cùng (root base) sẽ được khai báo trong file routes.rb Giờ cây thư mục của chúng ta sẽ như thế này.
app
|––controllers
|––api
|––v1
|––base.rb
|––users
|––base.rb
|––index.rb
|––show.
|––create.rb
|––destroy.rb
|––posts
|––base.rb
|––index.rb
|––show.
|––create.rb
|––destroy.rb
Theo như các bro đang thấy thì có thêm layer api và v1 dùng để đánh dấu, có thể sẽ có thêm web hoặc v2, v3 nữa, tùy vào yêu cầu dự án. Nhưng mà với các dự án trong cty của tôi thì chỉ có vậy thôi.
Đầu tiên, sửa lại routes.rb, root base giờ nằm ở bên trong thư mục api, không còn trực tiếp trong thư mục controllers nữa.
# config/routes.rb
Rails.application.routes.draw do
mount API::V1::Base, at: "/"
end
Root base sẽ như thế này
#app/controller/api/v1/base.rb
module API
module V1
class Base < Grape::API
include API::V1::Version
mount API::V1::Users::Base
# mount API::V1::Posts::Base
end
end
end
Base ở module sẽ như thế này
#app/controller/api/v1/users/base.rb
module API::V1::Users
class Base < Grape::API
resource :users do
mount API::V1::Users::Index
# mount API::V1::Users::Show
# mount API::V1::Users::Create
# mount API::V1::Users::Destroy
end
end
end
Ớ mà khoan, đặt tên thư mục là api thì module sẽ là Api::Base chứ không phải là API::Base. Giờ không lẽ phải đặt tên thư mục là a_p_i. Tới lúc này, các bro mở cái file config/initializers/inflections.rb ra, thêm như sau
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'API'
end
Giờ là lúc làm cái version v1 kia hoạt động, trong folder v1, các bro tạo một file version.rb. Version sẽ được include vào trong root base
module API
module V1
module Version
extend ActiveSupport::Concern
included do
prefix 'api'
version 'v1', using: :path
end
end
end
end
Để xem thử flow của chúng ta có hoạt động không, giờ hãy xóa file health_check.rb đi và viết lại một file users/index.rb.
# app/controllers/api/v1/users/index.rb
module API::V1::Users
class Index < Grape::API
get '' do
status :ok
content_type 'text/plain'
body 'Hello World'
end
end
end
Nếu ở http://localhost:3000/api/v1/users trả về data, tức là route của chúng ta đã hoạt động.
Comments