In this lesson, we will demonstrate how to create a new route that handles POST requests for inserting a new product into the database. This guide covers updating routes, implementing database methods for product insertion, creating the HTTP handler for the POST request, and testing the new endpoint.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Defining the Routes
First, update the routes in your application to include a new route for creating products. In addition to the existing routes for fetching products, we’ll add a route that handles POST requests for inserting new products.Implementing the Database Methods
Before handling the POST request, define the necessary methods on your product model.Fetching an Existing Product
First, verify the method for fetching a product from the database works correctly:Inserting a New Product
Next, implement the method that inserts a product into the database. This method constructs an INSERT query using the product’s name, quantity, and price. After executing the query, it retrieves the last inserted ID and assigns it to the product struct.If your database table contains more columns than these three, ensure you specify the exact columns in your INSERT statement.
Creating the Route Handler for POST Requests
Now, create the HTTP handler function that will process the POST requests. This handler is responsible for decoding the JSON payload sent by the client. If the payload cannot be decoded properly, the function returns an error response with the HTTP status “Bad Request”./product are routed to the createProduct function.
Testing the POST Endpoint
After building and running your application, test the new endpoint by sending a sample JSON payload. For instance, you can use a tool like Postman or curl to send a POST request to the/product endpoint with the following JSON:
This error indicates that the number of values provided in the INSERT statement does not match the columns in the products table. Verify your INSERT query to ensure the columns and values align correctly.
Verifying the Inserted Product
Finally, confirm that the new product has been inserted by accessing the GET endpoint for/products. A typical successful response may look like this:
This lesson covered updating routes, implementing model methods for data insertion, decoding JSON from POST requests, and testing the endpoint. Happy coding!