LoginSignup
0
0

More than 1 year has passed since last update.

APIとは・Railsへの導入の仕方

Posted at

そもそもAPIとは

APIは「Application Programming Interface」の略でわかりやすく説明すると『アプリケーションをプログラムして出来たインターフェース』となります。ソフトウェアの一部機能を共有する仕組みを指します。具体的には、「機能を公開しているソフトウェア」と「その機能を使いたいソフトウェア」をつなげる窓口のようなものです。
Web APIは、ひとことで言えば、インターネット(Web)を経由して、何らかの処理を行うための、手段や決めごと(API)のことです。
google apiや、amazon apiのように有名なWebAPIがあり、自分でWebAPIを作って自分だけで利用することも可能です。

APIを利用するメリット

APIを利用するメリットは、短期間でサービスを開発できる点にあります。APIを利用すると、その機能の開発を行う手間を省くことができるようになるため、開発期間の短縮やコストの削減が可能になります。

Web APIの仕組み

Web APIでは、Web APIで機能を公開しているサーバに対して、インターネットなどの通信ネットワークを通じて依頼内容をHTTPリクエストの形で送信すると、処理結果がHTTPレスポンスの形で送られてきます。送受信されるデータの形式はAPIによって様々だが、Webでよく用いられるXMLやHTML、JSON、各種の画像ファイル形式などが用いられることが多いです。

Rails APIの作成

APIモードでRailsアプリの作成

外部からPostというモデルの情報の作成・取得・削除・編集ができるような形式にします。
通常のrails newコマンドの末尾に--apiをつけることでAPIモードでアプリを作成することができます。
(APIに必要ない部分をデフォルトで作成しなくなります。)

$ rails new アプリ名 --api

モデル・コントローラの作成

通常のRailsアプリ同様モデルとコントローラを作成します。
今回はtitleというstringを持ったpostというテーブルを作成するとします。

$ rails g model post title:string
$ rails g controller posts
$ rails db:create
$ rake db:migrate

ルーティングの設定

最初から以下の様にバージョンで名前空間を作成しておくことで今後のAPIのバージョン管理が容易になります。

config/routes.rb
Rails.application.routes.draw do
  namespace 'api' do
    namespace 'v1' do
      resources :posts
    end
  end
end

コントローラの設定

posts.controller.rb
module Api
  module V1
    class PostsController < ApplicationController
      before_action :set_post, only: [:show, :update, :destroy]

      def index
        posts = Post.order(created_at: :desc)
        render json: { status: 'SUCCESS', message: 'Loaded posts', data: posts }
      end

      def show
        render json: { status: 'SUCCESS', message: 'Loaded the post', data: @post }
      end

      def create
        post = Post.new(post_params)
        if post.save
          render json: { status: 'SUCCESS', data: post }
        else
          render json: { status: 'ERROR', data: post.errors }
        end
      end

      def destroy
        @post.destroy
        render json: { status: 'SUCCESS', message: 'Deleted the post', data: @post }
      end
 end

引用記事

APIの仕組みが分かる・使いこなせる人材になれる記事(Pythonコード付き)
Web APIのメリットと探し方
WebAPIについての説明Railsで超簡単API
巨人の力を使っちゃえ!Web APIを使えば、あなたの夢も一発で実現

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