1
0

はじめに

最近、PostmanというAPIの開発をサポートしてくれるツールを知ったので使ってみようと思います。

Postmanとは

公式より

Postman は、 API を構築および使用するためのAPI プラットフォームです。Postman は、API ライフサイクルの各>ステップを簡素化し、コラボレーションを効率化することで、より優れた API をより迅速に作成できるようにします。

公式に書いてある通り、PostmanはAPIの開発やテスト等をサポートするツールです。
実際にAPIにGETやPOSTを行い、リクエストやレスポンスを受け取ることができます。

Postmanでrailsのcreateを行う

実際に、Postmanを使ってみようと思います。

Postmanをダウンロード

まずはPostmanをダウンロードします。

lightweight API clientで入る

lightweight API clientと表示されているところをクリックすると、アカウント作成なしでPostmanを使用できます。(アカウントなしの場合、一部機能が制限されています)
image.png

railsでcreateメソッドを実装する

scaffoldでusersテーブルとcontroller, view等を実装します。

rails g scaffold User name:string email:string

users_controller.rbに以下のコードが生成されていると思います。

app > controllers > users_controller.rb
# POST /users or /users.json
def create
  @user = User.new(user_params)

  respond_to do |format|
    if @user.save
      format.html { redirect_to user_url(@user), notice: "User was successfully created." }
      format.json { render :show, status: :created, location: @user }
    else
      format.html { render :new, status: :unprocessable_entity }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

外部でAPIをたたけるように、以下のコードを追加します。
これがないとCSRFトークンエラーでAPIを外部から実行できません。

app > controllers > users_controller.rb
class UsersController < ApplicationController
  before_action :set_user, only: %i[ show edit update destroy ]
+ protect_from_forgery with: :null_session, only: [:create]

Postmanで設定を行う

以下のように、POSTでhttp://localhost:3000/usersをたたいてuserをcreateします。
image.png

HeadersでContent-Type: application/json, Accept: application/jsonを設定し、JSONでリクエストとレスポンスをできるようにします。
image.png

Bodyでrawを選択し、JSON選びます。
そして、以下のコードを入力します。

{
      "name": "山田太郎",
      "email": "sample@sample.com"
}

image.png

Sendをクリックし、POSTを実行

Sendボタンをクリックすると、jsonがレスポンスで返ってきます。
リクエストのjsonのnameやemailを変更し、Sendするとレコードを作成してくれるので、テストデータを作成するときなどに便利そうですね。
image.png

GETを実行する

GETでhttp://localhost:3000/usersをたたくと、usersテーブルのレコードすべてが返ってきます。
image.png

終わりに

Postmanを使用して、railsのcreateを実行してみました。
Postmanがどういうものか簡単ですが、分ったと思います。
変数設定やAPIのテストも行えるみたいなので、気になる方はやってみてください!

参考

1
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
1
0