33
31

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.

WebAPIのダミーサーバをすぐに作る方法

Posted at

例えばWebAPIを叩いてデータ受信し処理するJavascriptとかを作ったりする時とかに、開発用のテストサーバとかって欲しい時ありませんか?

こんな勉強とか開発とかで使えそうなのはサクッといきたいところです。
こんな時はSinatraさんの出番です。

以下、Rubyとbundleが使える環境の前提です。

準備

セットアップ用にGemfileを作っておきます。

Gemfile
source :rubygems
gem 'sinatra'
gem 'sinatra-jsonp'

次に

$ bundle install

これで環境構築終わり

サーバを作ります

apiserver.rb
require 'sinatra'
require 'sinatra/jsonp'

list = [
  "1111",
  "2222",
  "3333"
]

keyvalues = {
  :name => "pakue",
  :no => 89
}

get '/array' do
  jsonp list
end

get '/farray' do
  jsonp list, "showValue"
end

get '/hash' do
  jsonp keyvalues
end

内容は何となく解ってもらえるかと。

サーバを起動します

サーバを起動します。

$ bundle exec ruby apiserver.rb

別の端末をたちあげて、curl使ってテストしてみます。

$ curl http://localhost:4567/array
["1111","2222","3333"]

$ curl http://localhost:4567/farray
showValue(["1111","2222","3333"])

$ curl http://localhost:4567/hash  
{"name":"pakue","no":89}
33
31
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
33
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?