I have to retuen the message "Data Added" in the api in ResponseBody Create a api while enters student data /newStudent
Request Body:
{
"name":"Shubham",
"rollno":22,
"studentid":1
}
Response:
{
"status":"OK",
"message":"Data Added"
}
@RequestMapping("/studentdata")
@ResponseBody
@ResponseStatus(HttpStatus.OK )
CodePudding user response:
You can create a custom response class that looks like this:
class CustomResponse {
private String status;
private String message;
// Constructor/Getters/Setters
}
Then in your controller return ResponseEntity
for example:
CustomResponse response = new CustomResponse("OK", "Data Added");
return ResponseEntity.ok(response); // the ok will return HTTP Status 200
Or if you want another HttpStatus, then you can use for example:
return new ResponseEntity<>(response, HttpStatus.CREATED);
^^^^^^^^^^^^^^^^^^
CodePudding user response:
This is how to return custom object in response.
router.post("/newStudent", async (req, res) => {
const { name, rollNo, studentId } = req.data;
// POST data to DB
const result = await AddStudentDataToDB({ name, rollNo, studentId });
res.status(200).json({
status: 'ok',
message: 'Data Added'
});
});
CodePudding user response:
First of all you should create a Response class which will hold status code and your custom message like the following class :
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Response {
private String statusCode;
private String statusMsg;
}
So in your controller where you post the object use ResponseEntity which can allow you to customize HTTP response methods. For example:
@Autowired
private StudentRepository studentRepository;
@PostMapping("/newStudent")
public ResponseEntity<Response> saveEmployee(@RequestBody Student
student){
studentRepository.save(student);
Response response = new Response();
response.setStatusCode("200");
response.setStatusMsg("Your message");
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}