3
4

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.

JsonWorldを利用してJSON SchemaとJSONを生成してみる

Posted at

@r7kamuraさん作のJsonWorldでJSON Schemaを生成できるモデルを作成します。

準備

JsonWorldについては@r7kamuraさん本人による下記のエントリをチェック

JsonWorldでモデルからJSON Schemaを生成する

サンプル

仕様

Railsのscaffoldで以下のモデルを作成しました。

attr type
People#name String
People#age Integer

Web キャプチャ

people_list.png

Resourceクラス作成

class PersonResource
  include JsonWorld::DSL

  property(
    :id,
    description: 'person id',
    example: 1,
    type: Integer,
  )

  property(
    :name,
    example: "tanaka",
    type: String,
  )

  property(
    :age,
    example: 34,
    type: Integer,
  )

  attr_reader :id, :name, :age

  # @param [Person] person
  def initialize(person)
    @id = person.id
    @name = person.name
    @age = person.age
  end
end

Controllerの修正

show を変更してみます

  • Before

scaffold直後の状態は下記です。

  # GET /people/1
  # GET /people/1.json
  def show
  end
  • After

Resourceクラスを呼び出すように変更します。

  # GET /people/1
  # GET /people/1.json
  def show
    respond_to do |format|
      format.html
      format.json { render json: PersonResource.new(Person.find(params[:id])) }
    end
  end

動作確認

  • curl で呼び出し
% curl http://172.16.33.100:3000/people/1.json
{"id":1,"name":"tanaka","age":23}
% curl GET http://172.16.33.100:3000/people/2.json
{"id":2,"name":"suzuki","age":42}
  • rails console でJSON-Schemaを確認
> puts PersonResource.to_json_schema
{
  "properties": {
    "id": {
      "description": "person id",
      "example": 1,
      "type": "integer"
    },
    "name": {
      "example": "tanaka",
      "type": "string"
    },
    "age": {
      "example": 34,
      "type": "integer"
    }
  },
  "required": [
    "id",
    "name",
    "age"
  ]
}

外部資料

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?