Make a Rails5 API that spits out JSON

This post is for me. Specifically to work with another app, which takes an api, and spits out a random question from another API.

create new rails app

rails new app_name --api

 

Create a table

rails g scaffold table_name attribute:type

 

We want a random question to be returned. In the Questions Controller, index method:

@questions = Question.order("RANDOM()").limit(1)

 

In order to allow the api to be accessed by a different app/url, add in application.rb:

 

config.action_dispatch.default_headers.merge!({
 'Access-Control-Allow-Origin' => '*',
 'Access-Control-Request-Method' => '*'
 })

 

Because I’m deploying with Heroku, which uses PostgresSQL (Not sqlite) in Gemfile, remove

gem 'sqlite3'

and replace with

group :development, :test do
 gem 'sqlite3'
 gem 'rspec-rails', '3.0.1'
end

group :production do
 gem 'pg'
 gem 'rails_12factor'
end

 

Create new git repo on github, and follow directions on pushing

Deploy to Heroku

heroku create, push, rake db, seed, open, et voila!

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s