Rails 5 Rails API 5
As you know, API applications don't have a user interface in the browser, instead, they only display JSON or XML data, etc. Therefore, when creating an API application, the writer should create the attached documentation to support the developers who use the API, especially QA. There are many ways to create a document, but the easiest way is to write it by hand, for example, an Excel or Word file. Specify what this API is for, what the URL is to access it, what data is sending the request, what is the response data to return, etc. If necessary, send it to the developer/QA side to use or read. This method is very manual and labor-intensive, but it isn't always of great value to those who use it. Because there is simply no unified format and it is easy to run out of information.
Rails 5 Rails API 5
As you know, API applications don't have a user interface in the browser, instead, they only display JSON or XML data, etc. Therefore, when creating an API application, the writer should create the attached documentation to support the developers who use the API, especially QA.
There are many ways to create a document, but the easiest way is to write it by hand, for example, an Excel or Word file. Specify what this API is for, what the URL is to access it, what data is sending the request, what is the response data to return, etc. If necessary, send it to the developer/QA side to use or read.
This method is very manual and labor-intensive, but it isn't always of great value to those who use it. Because there is simply no unified format and it is easy to run out of information.
1. Overview of Rails 5 API mode
Rails 5 is finally officially released, so let's take a look at the new additional features we use.
The first thing to talk about is the introduction of Rails 5's API mode. This allows you to build Web APIs without the hassle of previously having to include them in your controller.
1.1 What is Web API?
1.2 Origin of Rails 5 API mode
In reality, this feature is a Rails API project integrated into Rails 5.
1.3 How to use Rails 5 API mode
Creating a simple Rails API-only application is as follows:
rails new my_app --api
By using --api, the generated application reduces middleware, and instead of inheriting from ActionController :: Base with the ActionController :: API, it also does not create views/helpers/assets and ApplicationControllers. It is then added to the config/application.rb file, making the application Web API only.
class Application < Rails::Application
config.api_only = true
And you can easily develop your application just like a regular RoR application. The application has nothing because all the views, helpers, or assets are already in the client. Instead of a view, you probably use something like a serializer to build your JSON document.
1.4 Why should Rails API mode instead of Sinatra or Grape be used?
We are often asked why we use Rails to build Web APIs instead of using something more compact and simple, such as Grape or Sinatra. The framework can help build small applications. But in addition to ORMs, some builders, auto-reload capabilities, etc., you can quickly find the library you want to use. And finally, you can turn your application into a huge Rails application made up of different libraries. That's not bad.
This approach allows you to choose exactly which gem to use. However, deciding to use Rails is also a good choice over other options. In addition, there are many Rails handles available, so you don't have to look for another small framework (security, conditional GET, caching, etc.).
1.5 When to use Rails API mode
If your application is a Web API, you should only use Rails 5's API mode. This means that instead of sending HTML, it sends JSON or XML that is easy for the client to use and prefer to use. Rack middleware is a complete implementation of the pipeline design pattern, is very heavy, and is used for RoR to run on request and response objects.
Rack middleware is a complete implementation of the pipeline design pattern and is very often used in RoR to run on request and response objects. By default, Rails API-only applications come with limited middleware. This means that they have been reduced to unnecessary features. Adding middleware is as easy as adding a declaration line to the application.rb file. For example, where to add Rack:: Deflater to your API:
module Alexandria class Application < Rails::Application
config.api_only = true
2. It is the JSON API version that builds the Rails API
2.1 What is the JSON API?
The JSON API is a specification of how client requests for resources can be retrieved or modified, and how the server backs up those requests.
The JSON API is designed to minimize both the number of requests passed between the client and the server and the amount of data. This effect is achieved without compromising readability and flexibility.
2.2 How to format the data
The API JSON serialization data should include:
- The root level of the JSON API response is a JSON object.
- This object contains keys with top-level data.
- The key can be a single JSON object that represents a record, or a record. Refers to a collection of JSON objects. Contains data.
A JSON object represents a record that contains:
- The record's ID.
- The record type, that is, the name of a resource such as posts or cats.
- An attribute key that points to a JSON object that contains a key/value pair that represents the property of that record. If you have any properties displayed here, it depends on how you want to serialize your data.
- A random key for a relationship that points to a JSON object that describes the relationship between a resource and other JSON API resources.
2.3 Implement JSON API in Rails 5 API
gem install rails --pre
rails new catbook --api --database=postgresql
Now that the JSON API is the way to go and you have a basic understanding of how to format your data, let's build a JSON API.
Build a simple Rails 5 API that provides Cat's relevant data and its settings. Therefore, our app has two main resources: cats and hobbies. Cats have a lot of interests and my hobbies are a lot of cats. We have a many-to-many relationship.
- Step 1: Start
First, run on Rails 5:
Then go ahead, go into the directory and add the following gem to your Gemfile.
Next, you need to configure the JSON API API adapter. Create a file
ActiveModelSerializers.config.adapter = :json_api
Also, when receiving data (when jhacsh POST data to the server), JSON API
You need to make the app accept it. Add the following to the same file:
api_mime_types = %W(
Mime::Type.register 'application/vnd.api+json', :json, api_mime_types
Don't forget to set CORS at the end when using the Rack-cors gem.
- Step 2: Domain model
Create resources for Cat, Hobby, and Cat Hobbies. Migrate to Cat with the following properties:
class CreateCats < ActiveRecord::Migration[5.0]
create_table :cats do |t|
class CreateHobbies < ActiveRecord::Migration[5.0]
create_table :hobbies do |t|
And cat hobbies:
class CreateCatHobbies < ActiveRecord::Migration[5.0]
create_table :cat_hobbies do |t|
t.references :cat, index: true
t.references :hobby, index: true
Then use the association to set up the model.
class Cat < ApplicationRecord
has_many :hobbies, through: :cat_hobbies
class Hobby < ApplicationRecord
has_many :cats, through: :cat_hobbies
class CatHobby < ApplicationRecord
- Step 3: Root and controller
Set the router namespace in the following way:
namespace :api do not
namespace :v1 do you
resources :cats, except: [:new, :edit]
resources :hobbies, except: [:new, :edit]
And controller structure:
Note that there is no definition for the Cat Hobbies router. This is because users who use this data need to see related cats and hobbies, and related hobbies and hobbies, but not cat hobbies.
- Step 4: Serializer and JSON renderer
If a customer requests a record of a cat, we would like to include a record of the relevant hobby.
This means that when a customer requests a cat record, it will include the entire record of a particular hobby or related hobby.
2.5 Cat serializer
Next, define a cat serializer to serialize the cat's properties and related hobbies.
class CatSerializer < ActiveModel::Serializer
attributes :id, :name, :breed, :weight, :temperament
This tells Rail to include the relationship key that describes the data involved when serving the record to the cat. So, suppose you define Cats#index as follows:
class CatsController < ApplicationController
render json: Cat.all
You can see that there is a key relationship that describes the relevant hobby data for each cat. But I haven't sideloaded the data yet. There is no record of actual hobbies here. To sideload the data, it needs to be added to the controller.
render json: Cat.all, include: ['hobbies']
You now have a top-level key that contains a record of the actual hobbies associated with your cat's request.
2.6 Optimization: N + 1
However, this data is a bit slow to load at this time as it sends each cat's favorite request to the database one at a time. We are making the following two database requests.
Cat Load (0.4ms) SELECT "cats".* FROM "cats" INNER JOIN "cat_hobbies" ON "cats"."id" = "cat_hobbies"."cat_id" WHERE "cat_hobbies"."hobby_id" = $1 [["hobby_id", 1]]
Clean this up and query the database only once for all settings related to cats.
Change the rendering of the controller.
render json: Cat.includes(:hobbies), include: ['hobbies']
This modifies the query in the database as follows.
2.7 Hobby serializer
You may have noticed that the data provided in the Hobby record contains key relationships that point to the relevant cat descriptive data.
That's because I'm setting up my hobby serialization.
class HobbySerializer < ActiveModel::Serializer
attributes :id, :name
After a long development period with many test versions, Rails 5.0 with hundreds of developers and thousands of commits has become one of the most stable and complete Rails versions to date.
The release of Rails 5.0 proves that the Rails community is still very strong and evolving.
If you are considering offshore development, please feel free to contact us.
※Here is our contact information.
Account Manager: Quan (Japanese/English available)
Phone number: (+84) 2462 900 388
Please feel free to contact us for consultation/application by phone.