简体   繁体   中英

Ruby on Rails API for beginner json response

I am new to ruby on rails. I apologize early if this question might be dumb... but I can't figure this out and the tutorials I've seen is making this simple task confusing. Or I am just not understanding what I am missing or what to do... if a step by step tutorial may help, thanks!

My task to make a rails api that you can pass JSON to via postman/DH. The payload will be {"value": "foo"}. A '200 (OK)' Response with payload of {"value":"bar"}

No database needed, just a controller that takes in a payload and gives back a response.

This is what I do know...

  1. What I do know is how to create a rails api by "rails new testrails --api"
  2. Then going to my 'gemfile' and installing some kind of json to gems.
  3. Then... I mess with the 'route.rb' file in config and the controller in'apps'.
  4. I get lost here on what I need to do with the route file and controller...
  5. What ever steps come next.

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 $RAILS_ROOT/Gemfile ( $RAILS_ROOT stands for the root directory of your rails app), then

$ bundle install

Then add these lines to your $RAILS_ROOT/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM