What is the correct HTTP method for a create or update action in a Rails API?

时间:2015-10-29 15:50:14

标签: ruby-on-rails rest http ruby-on-rails-4

I'm creating an API which will be accessed in JavaScript. I want the user of the API to be able to send a request and create_or_update a record in the database. Should I be using the POST, PUT, or PATCH method for this request?

Is the following acceptable or is it outside of REST best practices?

# POST /objects
def create_or_update
  object = Object.find_or_create_by(params[:attribute])
  if object.update_attributes(object_params)
    render :json => {}, :status => :ok
  else
    render :json => {}, :status => :bad_request
  end
end

1 个答案:

答案 0 :(得分:5)

IMHO, most appropriate would be PUT. See HTTP 1.1, section 4.3.4 PUT, which is a "create or replace".