Updating and Deleting Resources with PUT, PATCH, and DELETE

Updating and Deleting Resources with PUT, PATCH, and DELETE

Welcome to this lesson focused on enhancing your skills in interacting with RESTful APIs by updating and deleting resources. In the previous lessons, you learned how to retrieve and create resources using the GET and POST methods. Now, you will explore the PUT, PATCH, and DELETE methods, which are crucial for modifying existing resources or removing them when they are no longer needed.

Understanding PUT, PATCH, and DELETE Methods

To effectively manage resources within an API, it's essential to understand how to use the following methods:

  • PUT: This method is used for completely updating a resource. You replace the current resource with the new data you provide in the request body. For example, if you're updating a to-do item, you'll include all the new details of the item in the body of the request and specify the resource ID in the request path to indicate which item you are updating.

  • PATCH: Use this method to make partial updates to a resource. You only need to include the specific fields you're updating in the request body. For instance, if you're only changing the description of a to-do item, you'll pass just the new description in the body. The resource ID is specified in the request path to identify which item is being modified.

  • DELETE: This straightforward method removes a resource from the server. You specify which resource to delete by including its identifier in the request path. No request body is needed since you're not sending any data, just instructing the server to remove the resource corresponding to that ID.

Successful requests using these methods typically return status codes of 200 (OK) or 204 (No Content). A 200 status code means the operation was successful and also returns content, such as a representation of the updated resource. In contrast, a 204 status code indicates success but with no content returned, meaning the server successfully processed the request but isn't providing any additional information. These methods are crucial for performing full CRUD (Create, Read, Update, Delete) functionality in API management. Let's delve deeper into each method and explore how they are implemented using Ruby.

Updating Resources with PUT

The PUT method is utilized when you need to update an entire resource. Imagine you have a to-do item that needs a complete overhaul, such as updating the task description, adding more details, or marking it as completed. The PUT request replaces the current resource representation with the new one you provide.

Here's an example of how to send a PUT request to update a to-do item:

require 'net/http'
require 'uri'
require 'json'

# Base URL for the API
base_url = "http://localhost:8000"

# Todo ID to update
todo_id = 1

# Updated todo data for PUT
updated_todo = {
  "title" => "Buy groceries and snacks",
  "done" => true,
  "description" => "Milk, eggs, bread, coffee, and chips."
}

# Create URI and HTTP request
uri = URI("#{base_url}/todos/#{todo_id}")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Put.new(uri.path, { 'Content-Type' => 'application/json' })
request.body = updated_todo.to_json

# Send PUT request
response_put = http.request(request)

# Check if the request was successful
if response_put.code.to_i == 200
  puts "Todo updated successfully with PUT!"
  puts JSON.parse(response_put.body)
else
  # Handle potential errors
  puts "Error updating the todo with PUT"
  puts "Status Code: #{response_put.code}"
  puts "Error Details: #{response_put.body}"
end

In this code, we specify the complete new data for the to-do item and send the request using the Net::HTTP::Put method. Upon receiving a 200 status code, you know the update was successful, and you can print the new representation of the to-do item. It's important to note that for our API, a PUT request requires all fields (title, description, and done) to be provided. If any field is missing, the request will fail and return a status code of 400. In cases where you only need to update specific fields, rather than the entire resource, the PATCH method is more suitable.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal