Welcome to this lesson, where we will focus on handling PUT and DELETE requests to update and delete resources in a web application using the Gin framework. In previous lessons, you've become familiar with setting up a Gin application and handling GET and POST requests. As a quick reminder, Gin is a popular framework in the Go language used to build web applications and APIs efficiently.
Before we dive into the examples, let's briefly go over what PUT and DELETE HTTP methods entail. As part of the fundamentals of building RESTful APIs, these methods play a critical role:
-
PUT: This method is used to update existing resources. For instance, if your to-do app has a task with certain attributes, using a PUT request, you can change those attributes to different values.
-
DELETE: This method is used to remove resources. When a task is completed and no longer needed in your to-do list, a DELETE request will remove it.
Understanding these methods is crucial as they allow you to modify the state of resources within your web application.
To handle a PUT request that updates a todo item by its ID, you'll need to understand what kind of data is being sent. Here's an example JSON body that you might send with a PUT request to update a todo item:
This JSON object represents a todo item with the title
attribute and a completed
status. These are the fields that can be updated.
Let’s look at the code to implement this:
router.go
:
controllers.go
:
services.go
:
Now, we'll look at implementing a DELETE request to remove a todo item using its ID:
router.go
:
controllers.go
:
services.go
:
- Extracting and Validating the ID: Similar to PUT, the ID is extracted from the path and validated. Any errors in conversion result in a
BadRequest
response. - Router Setup and Handler Function: The DELETE route is defined in the router setup and linked to the
DeleteTodo
handler function. This function manages the removal process and returns appropriate HTTP status codes. - Finding and Removing the Resource: The function in the business logic package iterates through the list to find the todo with the matching ID and removes it from the slice using optimized slice operations.
In this lesson, you learned how to handle PUT and DELETE requests with Gin. We explored how these HTTP methods work within RESTful APIs and walked through implementing them in code with practical examples. Understanding how to update and remove resources is fundamental as you continue to build dynamic web applications.
Get ready to apply what you've learned through upcoming practice exercises that will reinforce your understanding by implementing these techniques on your own. You are making excellent progress — keep experimenting and practicing to deepen your knowledge and skills further!
