Creating a REST API with Rails
Rails has the ability to create API-only applications. This results in a lighter-weight app that is more conducive to creating SPAs.
-
First, let’s create an API only version of our blog app.
rails new color_list_api_rails --api
-
Next, we generate the model for authors
bin/rails g scaffold Color title:string uuid:string color:integer rating:integer
-
Run the migration:
bin/rails db:migrate
-
Let’s seed the database with some colors.
Color.create(title: 'Ocean at noon', color: 0x029eb6, rating: 5, uuid: '0175d1f0-a8c6-41bf-8d02-df5734d829a4')
Color.create(uuid: "83c7ba2f-7392-4d7d-9e23-35adbe186046",title: "Lawn",color:0x2534486, rating:3)
Color.create(uuid: "a11e3995-b0bd-4d58-8c48-5e49ae7f7f23",title: "Bright red",color: 0x16711680,rating:2)
Color.create(uuid: "49fef18c-475c-4ff7-b2de-7adfdbcbaa24",title: "Orange",color:0xca8102,rating: 0)
bin/rails db:seed
-
Now just launch the server
bin/rails server
and go to the
colors
route. -
A few things to notice:
- There are no
new
andedit
routes: An API doesn’t use forms, so we don’t need a route to display a form. - There are no views for
Color
- There are no
CORS (Raw)
Generally speaking, conventional browsers implement a same-origin security policy when it comes to AJAX fetches. That is, AJAX fetches to domains different from the page from which they are made are blocked by default.
Cross-origin resource sharing (CORS) is a standard that allows a web browser and server to interact in a way that permits cross-origin AJAX calls from a browser to a server. In order to use our Rails API-only app, we need to enable CORS on it.
We can do this the “raw” way by adding the header manually: Add the following to index
in the controller.
response.headers["Access-Control-Allow-Origin"] = "http://localhost:3000"
CORS (package)
To do this, you need to include the following in the Gemfile
of your rails app:
gem 'rack-cors', :require => 'rack/cors’
Don’t forget to run the bundle install
command after updating the Gemfile
:
bundle install
Finally, create a new file, config/initializers/cors.rb
with the following content:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'http://localhost:3000'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Note that this configuration expects your React app to be running on port 3000. If you are using a different port, adjust the line above accordingly. (By default, Rails runs on port 3000 also; so, if you are running both Rails and React locally, you will have to pick a different port for one of them.)