LoginSignup
0
0

Rails APIエンドポイントの作成:基本操作

Last updated at Posted at 2024-01-23

はじめに

この記事では、Railsを使用して基本的なAPIエンドポイント(POST、PUT、GET、DELETE)を作成する方法をメモっぽく記載しておきます。

必要なもの

  • Ruby on Rails
  • RESTful APIに関する基本的な理解

ステップ 1: Railsのセットアップ

まずは、新しいRailsプロジェクトを作成する。ターミナルで以下のコマンドを実行

rails new my_api_project --api
cd my_api_project

このコマンドにより、API専用のRailsプロジェクトが作成される。

ステップ 2: モデルの作成

今回はブログの記事を管理するためのArticleモデルを作成します。次のコマンドを実行

rails generate model Article title:string body:text
rails db:migrate

ステップ 3: コントローラの設定

Articlesコントローラを作成し、CRUD操作(作成、読み取り、更新、削除)を実装します。

rails generate controller Articles

app/controllers/articles_controller.rbに以下のようなメソッドを追加。

class ArticlesController < ApplicationController
  # 各メソッドの実装
end

ステップ 4: ルーティングの設定

config/routes.rbにルートを設定して、リクエストをコントローラのアクションに分けます。

resources :articles

ステップ 5: 各アクションの実装

  • POST (Create): 新しい記事を作成する。
  • GET (Read): 一覧表示や特定の記事を取得する。
  • PUT (Update): 既存の記事を更新する。
  • DELETE (Destroy): 記事を削除する。

各アクションの詳細なコードは以下の通り(例としてcreateアクション)。

def create
  @article = Article.new(article_params)
  if @article.save
    render json: @article, status: :created
  else
    render json: @article.errors, status: :unprocessable_entity
  end
end

ステップ 6: テスト

Postmanなどのツールを使用して、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