2
1

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.

[Ruby] SinatraでMysqlのデータを返却するjson APIを作る

Last updated at Posted at 2016-10-10

前の記事とかでMysqlに貯めたデータを外から使いたいと思ってSinatraでjsonAPI化したので手順をメモ。
mysql2でやったけど、本来はActiveRecordとかを使うべきなのかもしれない。

下準備

必要なGemをインストール

gem install mysql2
gem install sinatra
gem install json

テーブルを作成

サンプル用のテーブルを作成。作成後適当なデータをinsertしておく。
既になにかしらデータの溜まったテーブルがあるならそれを使えばいいです。

mysql> CREATE TABLE `data` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Title` varchar(256) DEFAULT NULL,
  `URL` varchar(512) DEFAULT NULL,
  `Created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

mysql> desc data;
+--------------+--------------+------+-----+-------------------+----------------+
| Field        | Type         | Null | Key | Default           | Extra          |
+--------------+--------------+------+-----+-------------------+----------------+
| Id           | int(11)      | NO   | PRI | NULL              | auto_increment |
| Title        | varchar(256) | YES  |     | NULL              |                |
| URL          | varchar(512) | YES  |     | NULL              |                |
| Created_at   | timestamp    | NO   |     | CURRENT_TIMESTAMP |                |
+--------------+--------------+------+-----+-------------------+----------------+

API部分のコード

mysql2で取得したレコードを1行づつ配列に格納した後to_jsonでjson化、APIのレスポンスとする。
不要なカラムがある場合は、sqlで落とす他にto_jsonの引数で取捨選択することも出来る模様。

api.rb
require 'sinatra'
require 'mysql2'
require 'json'
require 'yaml'

get '/api' do
  content_type 'application/json'
  db_to_json
end

def db_to_json
    client = Mysql2::Client.new(YAML.load_file('database.yml'))
    sql = "select * from data limit 10" #10件分取得

    ary = Array.new
    client.query(sql).each {|row| ary << row}
    return ary.to_json
end

DBの設定ファイル

database.yml
database: データベース名
host: localhost
username: ユーザ名
password: パスワード

リクエストしてみる

sinatraを起動

$ ruby api.rb

wgetでアクセス(jqで整形)

$ wget -O - "http://localhost:4567/api" | jq .
[
  {
    "Id": 1,
    "Title": "MechanizeでTwitterアナリティクスのデータエクスポートを自動化する",
    "URL": "http://qiita.com/Feburic/items/20590d02152e06faf502",
    "Created_at": "2016-10-10 02:16:00 +0900"
  },
  {
    "Id": 2,
    "Title": "Amazonの商品ページURLフォーマットに関するメモ",
    "URL": "http://qiita.com/Feburic/items/6e918b1a9345367622c9",
    "Created_at": "2016-10-10 02:16:00 +0900"
  }
]

うまいこと動いてるっぽい。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?