DEV Community

dandanthemanman
dandanthemanman

Posted on

Write an API patch route in Sinatra

While learning to write Sinatra API routes, the PATCH route was the most confusing for me. If you're in the same boat, the following 5 steps should help.

Before we start, you need to make a ruby file called "application_controller.rb" in app/controllers.

First: In the new file declare the class ApplicationController.

class ApplicationController < Sinatra::Base

end
Enter fullscreen mode Exit fullscreen mode

Second: Write the method "patch"
Add the model where the instance you're changing lives.
Add "/:id" to the end.

class ApplicationController < Sinatra::Base

patch "/table/:id" do

end

end
Enter fullscreen mode Exit fullscreen mode

Third: Use find() and the params id to locate the instance in the model, and declare a variable with it.

class ApplicationController < Sinatra::Base

patch "/desiredtable/:id" do
desiredRecord = DesiredModel.find(params[:id])
end

end
Enter fullscreen mode Exit fullscreen mode

Fourth: Now, we'll update this variable's attribute.
Update it with the value we pull from the params.

class ApplicationController < Sinatra::Base

patch "/desiredtable/:id" do
desiredRecord = DesiredModel.find(params[:id])
desiredRecord.update(attribute: params[:attribute])
end

end
Enter fullscreen mode Exit fullscreen mode

Fifth: (last but certainly not least) Convert the variable to JSON.

class ApplicationController < Sinatra::Base

patch "/desiredtable/:id" do
desiredRecord = DesiredModel.find(params[:id])
desiredRecord.update(attribute: params[:attribute])
desiredRecord.to_json
end

end
Enter fullscreen mode Exit fullscreen mode

Done!

Top comments (0)