0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

APIの3つの作り方

Last updated at Posted at 2019-07-11

APIの3つの作り方について解説する。

APIとは?

APIとは、JavaScriptやjQueryを用いたAjax通信を行う際、必要なデータのみをJSON形式で返すサーバの仕組みのことをいう(JSON API)。

APIの3つの作り方

1.既存のコントローラを共用してAPIとして使えるようにする方法

respond_to メソッドを使い、コントローラーでHTMLとJSONを返すための処理を条件分岐させる。


respond_to do |format|
  format.html 
  format.json 
end

2.新たに、API専用のコントローラーを作成する方法

コントローラ以下のディレクトリにAPIのファイルを作成する。

controllers/api/コントローラ名_controller.rb

もしも、APIのコントーローラと同じ名前のコントローラがすでに存在している場合は、名前空間(namespace,::)をつけることにより、それらを区別することができる。


class Api::コントローラ名Controller < ApplicationController
 
end

ちなみに、この場合、ルーティングの設定方法が通常と異なる。


namespace :api do
 resources :messages, only: :index, defaults: { format: 'json' }
end

3.APIを作成するためのgemを利用する方法

rails-apiなどのgemをインストールするとできるようである(gemを利用したAPI作成ををまだ行なったことがない。)

詳しくは、以下の記事を参照ください。
https://www.sejuku.net/blog/10906#RailsAPI-2

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?