johnsorrentino
johnsorrentino

Reputation: 2731

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

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

Upvotes: 2

Views: 1590

Answers (1)

CouchDeveloper
CouchDeveloper

Reputation: 19106

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

Upvotes: 5

Related Questions