mo-fu note

研究からキックボクシングまで何でも書いていきます!

RailsAPIのエンドポイントに.jsonを付けずにjson形式でレスポンスを返す方法

Railsでjbuilderなどを使ってAPIを作っている時に、 http://localhost:3000/api/microposts/feed_items.json みたいに .json を付けたくないなーと思っていた。 調べたら、以下のように config/routes.rb で defaults の format として jsonを指定すれば、 拡張子無しで http://localhost:3000/api/microposts/feed_items のようにアクセスしてもjsonを返すことができた。

サンプルコード

  • Rails 4.2.3
  • jbuilder 2.2.3

config/routes.rb

namespace :api, defaults: { format: 'json' } do
  get 'microposts/feed_items'
end

app/views/api/microposts/feed_items.json.jbuilder

json.array! @feed_items

app/controllers/api/microposts_controller.rb

class Api::MicropostsController < Api::ApplicationController
  def feed_items
    @feed_items = current_user.feed
  end
end

(modelのコードなどは省略)

.json拡張子を外してリクエストを送信

httpie を使ってリクエストを送ってみる。 http http://localhost:3000/api/microposts/feed_items を実行。

実行結果

HTTP/1.1 200 OK
Cache-Control: max-age=0, private, must-revalidate
Connection: Keep-Alive
Content-Length: 297
Content-Type: application/json; charset=utf-8
Date: Thu, 13 Aug 2015 16:18:29 GMT
Etag: W/"45fcd45ed079622eb16231cc6cfc0b34"
Server: WEBrick/1.3.1 (Ruby/2.2.2/2015-04-13)
Set-Cookie: request_method=GET; path=/
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: dc4d3221-6c68-4dbe-8687-360148d49461
X-Runtime: 0.010985
X-Xss-Protection: 1; mode=block

[
    {
        "content": "test test2222",
        "created_at": "2015-07-28T14:15:22.000Z",
        "id": 2,
        "picture": {
            "url": null
        },
        "updated_at": "2015-07-28T14:15:22.000Z",
        "user_id": 1
    },
    {
        "content": "test test",
        "created_at": "2015-07-28T14:14:33.000Z",
        "id": 1,
        "picture": {
            "url": null
        },
        "updated_at": "2015-07-28T14:14:33.000Z",
        "user_id": 1
    }
]

.json のように拡張子をつけなくても、json形式で返ってきた。

http http://localhost:3000/api/microposts/feed_items.json のように、 .json を付けても同じ結果となった。

参考サイト