Help us understand the problem. What is going on with this article?

Rails5のAPI modeをサクッと構築してみる

More than 3 years have passed since last update.

以下、API mode をサクッと初期構築するための手順メモです。


作りたいアプリのフォルダを用意する。

$ mkdir sample_api_app
$ cd sample_api_app

Rails5 ではバージョン2.2.2以上の Ruby が必要なので、rbenv などでバージョンを変更する。
(今回 rbenv のインストール方法については記載しません)

$ rbenv install -v 2.3.3
$ rbenv local 2.3.3
$ ruby -v # バージョンを確認

Gemfile を生成する。

$ gem install bundler
$ bundle init

Gemfile にある Rails の記載をコメントアウトし、バージョンを 5 にする。

$ vi Gemfile

↓↓↓

Gemfile
# A sample Gemfile
source "https://rubygems.org"

# Comment out and set version
gem "rails", "~> 5.0"

Rails をインストールし、API mode で初期構築する。
(rails new 時に --api をつけるだけです)

$ bundle install --path vendor/bundle
$ bundle exec rails new . --skip-bundle --api    # すべてYでよい
$ bundle update

User の CRUD を作成する。

$ bundle exec rails g scaffold User name:string age:integer
$ bundle exec rake db:create
$ bundle exec rake db:migrate

Rails サーバーを起動する。起動はやい。

$ bundle exec rails s
=> Booting Puma
=> Rails 5.0.0.1 application starting in development on http://localhost:3000
# frozen_string_literal: true
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.6.2 (ruby 2.3.3-p222), codename: Sleepy Sunday Serenity
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

curl で疎通テストをしてみる。

$ curl http://localhost:3000/users
[]%
$ curl http://localhost:3000/users -X POST -d 'user[name]=shibukk&user[age]=76'
$ curl http://localhost:3000/users
{"id":1,"name":"shibukk","age":76,"created_at":"2016-12-13T01:55:15.528Z","updated_at":"2016-12-13T01:55:15.528Z"}%

いけました :thumbsup:

shibukk
東京で AWS と Rails をちょっとだけやっています。あと GCP も。
https://www.flickr.com/photos/158672816@N06/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした