RESTful API using Grape in Rails
Grape is a REST-like API framework that can be used to complement existing web applications in Rails.
Installation:
Here, we will walk through a basic CRUD application that is integrated by grape API. We will use 2 gems.
gem 'grape' gem 'grape_on_rails_routes'
The gem ‘grape’ will help us build the API from our Rails backend.
The grape_on_rails_routes allows us to easily read and write routes created by our Grape API.
Configuration:
To let our application know the API path, add the following in application.rb:
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb') config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
In routes.rb, we will add the next line of code, which points to a base class of our module. In this way, we do not need to add routes for each action, as the base class will point to each action of our class.
mount MusicStore::Base => '/'
Inside the app, we will create a folder for our API. Inside this API folder, we can create separate folders for our modules. Today, we will make a music store, so a folder named music_store needs to be created at first inside the API folder. The base class will be placed under each module folder and the following code needs to be added there.
app/api/music_store/base.rb module MusicStore class Base < Grape::API mount MusicStore::V1::Songs end end
Inside each module folder, we can create separate folders for versioning. We will create a v1 folder inside the music_store folder, under which will create our class songs.rb. The folder structure is as such: app/api/music_store/v1/songs.rb
Inside songs.rb, let us create our songs class inside our MusicStore module. We will only mention our versioning folder. The path does not need to be explicitly declared as it is already set in the base class. On exposing the API, the data will be sent in JSON format, thus we will declare the format and prefix here.
module MusicStore module V1 class Songs < Grape::API version 'v1', using: :path format :json prefix :api end end end
POST request: /api/v1
Let us first create a song. The most basic and mandatory POST request is for creating an object. Here we will add the following code, which takes in three parameters that contains field values of the Song object and will create a song in the method. The params block denotes which parameters are mandatory. After the params block, the POST method starts, which takes in the parameters and create our object.
desc 'create a new song' params do requires :name, type: String requires :singer, type: String requires :rating, type: Float end post do Song.create!({ name:params[:name], singer:params[:singer],rating:params[:rating]}) end
e.g: /api/v1?name=Diamonds&song=Rihanna&rating=4.8
GET request: /api/v1/songs
Add the following to fetch/retrieve the list of saved songs.
resource :songs do desc 'Return list of songs' get do Song = Song.all present song end end
To get a specific song, the corresponding id needs to be passed through the API. The route_param will take the id that needs to be fetched. Then in the GET method, that specific object is fetched and returned through the present.
GET request: /api/v1/:id
desc 'Return a specific song' route_param :id do get do song = Song.find(params[:id]) present song end end
PUT request: /api/v1/:id
The PUT request allows us to update a specific object, provided its id. The route_param will take the object id and inside the PUT method that object will be fetched and updated with the values passed in the parameter.
desc 'Update a specific song' route_param :id do put do Song.find(params[:id]).update({ rating:params[:rating] }) end end
DELETE request: /api/v1/1
To delete an object simply pass the object id to the delete method.
desc 'Delete a specific song' route_param :id do delete do song = Song.find(params[:id]) Song.destroy end end
You can see the list of grape API routes by running :
rails grape:routes or rake grape:routes
Our application will return the following:
GET | /api/:version/songs(.json) | v1 | Return list of songs GET | /api/:version/:id(.json) | v1 | Return a specific song PUT | /api/:version/:id(.json) | v1 | Update a specific song DELETE | /api/:version/:id(.json) | v1 | Delete a specific song POST | /api/:version(.json) | v1 | create a new song
Summary:
Thus, at the end of implementing our project, we’ll be able to create, update, delete, show a song or get the list of the total songs, by calling the API routes.
Here’s the GitHub link to this project for further reference:
https://github.com/mehreenmansur/music-grape-api
Contributor: Mehreen Mansur, Nascenia
No comments