Now that we are able to get multiple records or a single record, let's see how we can do adding a new record. So to do that, let's go to our application, customer rest controller. Let's add a new function here, public response entity of question mark, add a new customer, we receive a customer object. And then I'd say report dot save the customer. Now, this actually adds the data that is coming from the parameter into the database automatically, because an assumption here is the customer ID is null and that customer object will be inserted into the database. The newly generated ID will be automatically set to this customer.
And then I can simply say here, return a response entity dot Okay with the customer object like this, and we have to add here at the rate post mapping to say that any request for slash API slash customers with the HTTP method called post should be handled by this particular function. Now the question is, how can spring give me a customer object How can as a user supply the customer object. Now if you come to postman and choose a POST method for slash API slash customers, you can see that there is an option here called body and this is called request body or payload. And you can supply a form data with a name value pairs. Similarly, www form URL encoded. Then there is a raw and then you can choose the type of text to be JSON or XML or plain text.
So we are sending the actual customer data in JSON format. But that's a request body. So we have to tell spring that hey, that data coming from the request body should be converted into a customer object if possible. And then that customer object is now taken and added to the database. To do so all I have to do is to write at the rate request body. And now spring knows where to look for a customer details when a POST request is made.
Now let's give it a try by going back over here we are sending a POST request to localhost double seven double seven slash API slash customers. And that's what actually this is mapped to two APA customers post mapping, but we have to send the body I'm going to send a body here that contains the name of the customer. Let's add my name. Let's say email. We know not.co. And let's add a phone number.
Gender, city, Bangalore. State, Nautica and country is India. Now all I have to do is to send this not that I'm not sending ID, but the response should be the same details with the newly generated ID. So let's click on the send button and see everything is okay. And as you can see that Id 1001 has been generated. And that response is 200.
All I have to do was to read the data from the request body and save into the database and then send the same customer back. So if I go back to the browser, where my database I have access to here, so let's go Connect. And then I can even check Select star from from customers where ID equals to 1001 click the Run button. I should see the same data that I have sent from postman. It has been added successfully as well.