This article explains how to implement a GET method for a Products API, including response handling, database querying, and testing with Postman.
In this guide, we implement the GET /products endpoint, which retrieves all product records from the database table and returns them as a JSON response. The following sections detail the implementation steps along with code snippets.
Before handling any routes, we create two helper methods: one for sending a successful response and another for sending error messages in JSON format.The first helper method, sendResponse, takes the response writer, an HTTP status code, and a payload (of any type). It marshals the payload into JSON and sends it to the client.
Similarly, the sendError method accepts a response writer, a status code, and a string error message. It constructs an error message map and returns it using sendResponse.
The next step is to define the route handler for the GET /products endpoint. This handler is implemented as a method on the App struct. Inside the handler, products are retrieved from the database using a dedicated function. If an error is encountered, sendError is used with an HTTP 500 status. Otherwise, the products are returned with an HTTP 200 OK status.
For clearer code organization, create a separate file (e.g., model.go) for database-related methods. Define the product struct with appropriate JSON tags to represent a product record from the products table.
Copy
Ask AI
package maintype product struct { ID int `json:"id"` Name string `json:"name"` Quantity int `json:"quantity"` Price float64 `json:"price"`}
Next, implement the getProducts function. This function accepts a database pointer and retrieves all products by executing a SELECT query. It iterates over each row and appends the product struct to a slice.
In the App initialization method, a connection to the MySQL database is established and the router is initialized. The DB pointer is assigned to app.DB, and the routes are set up by calling handleRoutes.
With the GET endpoint successfully implemented and tested, consider extending your inventory API by adding additional routes such as creating, updating, and deleting products.Happy coding!