LoginSignup
5
5

More than 5 years have passed since last update.

SinatraでJSONを受け取る方法

Last updated at Posted at 2018-04-02

SinatraでJSONを受け取る方法。

結論: Rack::PostBodyContentTypeParser を使う。

やり方

rack-contribをインストールする

Gemfile
gem 'rack-contrib'

or

$ gem install rack-contrib

Rack::PostBodyContentTypeParserを有効にする

app.rb
require 'sinatra'
require 'rack/contrib'

use Rack::PostBodyContentTypeParser

post '/hoge' do
  params[:foo]
end

動作確認

$ curl -X POST -H 'Content-Type: application/json' -d '{"foo": "bar"}' http://localhost:4567/hoge

bar

ただし、リクエストのContent-Typeapplication/jsonである必要があるので注意。

5
5
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
5
5