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:
- Parsing the ID: The path parameter
:idis extracted from the URL and converted to an integer. We handle any errors that might arise if the ID provided is invalid. - Binding JSON Data: The
c.ShouldBindJSONmethod is used to bind the incoming JSON payload to theupdateDatavariable, which is of typeTodo. If this binding fails, due to invalid JSON format for instance, aBadRequestresponse is returned. - Router Setup and Handler Function: We define the PUT route in the router setup. The route is connected to the
UpdateTodohandler function, which handles the logic of managing HTTP status codes and binding JSON data. - Business Logic and Updating the Resource: The
UpdateTodoServicefunction in the business logic package is responsible for the actual updating of the todo item. It loops through thetodoslist to find the matchingTodoby ID and updates theTitleandCompletedfields. - Response Handling: If the todo is successfully updated, the new data is sent back with a
StatusOKresponse. If no matching todo is found, aNotFoundresponse is returned.
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
BadRequestresponse. - Router Setup and Handler Function: The DELETE route is defined in the router setup and linked to the
DeleteTodohandler function. This function manages the removal process and returns appropriate HTTP status codes. - Finding and Removing the Resource: The
DeleteTodoServicefunction in the business logic package iterates through thetodoslist to find the todo with the matching ID and removes it from the slice using optimized slice operations. - Response Management: A successful deletion results in a
StatusOKresponse with the removed todo. If the todo is not found, aNotFoundresponse is provided.
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!
