Skip to content

Instantly share code, notes, and snippets.

@jendiamond
Created March 31, 2017 08:29
Show Gist options
  • Save jendiamond/d7459488cf73efd60bbff00da35c5e61 to your computer and use it in GitHub Desktop.
Save jendiamond/d7459488cf73efd60bbff00da35c5e61 to your computer and use it in GitHub Desktop.

Build a RESTful JSON API With Rails 5 – Part One -Jan 31, 2017

How to Make a Rails 5 App API-Only June 30, 2016

Building a JSON API with Rails 5 - September 24, 2015

http://stackoverflow.com/questions/42688328/ruby-on-rails-api-for-beginner-json-response

Step 1: install Rails 5

$ gem install rails

Step 2: create an API-only Rails application

$ rails new my_app --api

Step 3: integrate rack-cors

Add gem 'rack-cors' at the bottom of your Gemfile

($RAILS_ROOT stands for the root directory of your rails app), then

$ bundle install

Then add these lines to your config/application.rb inside the class definition

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :patch, :put, :delete, :options]
  end
end

Step 4: generate a controller

$ rails g controller foo

Add an action to the FooController (in file $RAILS_ROOT/controllers/foo_controller.rb)

def create
  foo = params[:foo]
  # Do whatever you want with foo
  render json: {value: 'bar'}
end

Step 5: Add a route

Modify the file $RAILS_ROOT/config/routes.rb, add

post '/foo' => 'foo#index' in the block

Step 6: start rails server

$ rails s

That's all. Now you can send POST requests to http://localhost:3000/foo and see what happens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment