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 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 Kotlin.

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:

Kotlin
1// Define the data class 2@Serializable 3data class Todo(val title: String, val done: Boolean, val description: String) 4 5// Todo ID to update 6val todoId = 1 7 8// Updated todo data for PUT 9val updatedTodo = Todo( 10 title = "Buy groceries and snacks", 11 done = true, 12 description = "Milk, eggs, bread, coffee, and chips." 13) 14 15// Convert to JSON 16val jsonData = Json.encodeToString(updatedTodo) 17 18// Create the request 19val request = Request.Builder() 20 .url("$baseUrl/todos/$todoId") 21 .put(RequestBody.create(MediaType.get("application/json"), jsonData)) 22 .build() 23 24// Perform the request 25client.newCall(request).execute().use { response -> 26 if (response.isSuccessful) { 27 println("Todo updated successfully with PUT!") 28 println(response.body()?.string()) 29 } else { 30 println("Error updating the todo with PUT") 31 println("Status Code: ${response.code()}") 32 println("Error Details: ${response.body()?.string()}") 33 } 34}

In this code, we specify the complete new data for the to-do item and send the request using OkHttp. 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 to be provided. If any field is missing, the request could 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.

Partial Updates with PATCH

Unlike PUT, the PATCH method is specifically designed for partial updates. When you need to modify only a specific field of a resource, PATCH ensures system efficiency and data integrity without the need to send a full representation.

Here's an example of performing a PATCH request on a resource:

Kotlin
1// Partial updated data 2val patchData = Json.encodeToString(mapOf("description" to "Updated description")) 3 4// Create the PATCH request 5val patchRequest = Request.Builder() 6 .url("$baseUrl/todos/$todoId") 7 .patch(RequestBody.create(MediaType.get("application/json"), patchData)) 8 .build() 9 10// Execute the PATCH request 11client.newCall(patchRequest).execute().use { response -> 12 if (response.isSuccessful) { 13 println("Todo updated successfully with PATCH!") 14 println(response.body()?.string()) 15 } else { 16 println("Error updating the todo with PATCH") 17 println("Status Code: ${response.code()}") 18 println("Error Details: ${response.body()?.string()}") 19 } 20}

In this scenario, only the description field is updated. After sending the PATCH request through OkHttp, we can check the response status code to confirm success. Successful updates with a status code of 200 allow you to view the updated resource fields, while any errors are managed by inspecting and printing error details.

Deleting Resources with DELETE

After learning how to update resources using PUT and PATCH, let's move on to deleting resources with the DELETE method. This method is straightforward — it's used to remove a resource from the server, which is important for keeping your data clean and relevant.

Here's how you can perform a DELETE request:

Kotlin
1// Todo ID to delete 2val todoDeleteId = 3 3 4// Create the DELETE request 5val deleteRequest = Request.Builder() 6 .url("$baseUrl/todos/$todoDeleteId") 7 .delete() 8 .build() 9 10// Execute the DELETE request 11client.newCall(deleteRequest).execute().use { response -> 12 if (response.code() == 204) { 13 println("Todo deleted successfully!") 14 } else { 15 println("Error deleting the todo") 16 println("Status Code: ${response.code()}") 17 println("Error Details: ${response.body()?.string()}") 18 } 19}

In this example, we're sending a DELETE request to remove a specific to-do item by specifying its ID in the request path. When the server successfully deletes the resource, you will typically receive a 204 status code. This code means "No Content," indicating that the deletion was successful, but there's no additional data to send back.

However, it's important to note that some services might return a 200 status code along with some content, such as a message. This can vary depending on how the service is designed, so always check the API documentation for specifics on how it handles deletions.

Summary and Preparation for Practice Exercises

This lesson provided you with a comprehensive understanding of the PUT, PATCH, and DELETE methods, enhancing your ability to modify and manage resources through API interactions. You learned how to update complete resources with PUT, make partial modifications with PATCH, and delete resources using DELETE. Understanding these operations is key to mastering CRUD functionality in RESTful API management.

As you proceed to the practice exercises, you're encouraged to apply these concepts to reinforce your understanding and learn through practice. Each operation is a building block toward becoming proficient in interacting with APIs using Kotlin. Keep up the great work as you progress through the exercises, further cementing your knowledge and skills in API resource management!

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