Issue
I'm learning REST API. I'm trying to delete an element from the list. I tried but getting an error on the postman. Can anyone help me where I went wrong? Also, can we return the object after deleting it? I also tried it but I think I'm messing up in delete code. So it was not working.
Here is the controller code:
@RestController
public class SpringRestController {
@Autowired
private CourseService courseService;
//Get the courses
@GetMapping("/courses")
public List<Course> getCourses()
{
return this.courseService.getCourses();
}
@GetMapping("/courses/{courseId}")
public Course getCourse(@PathVariable String courseId)
{
return this.courseService.getCourse(Long.parseLong(courseId));
}
//Add a course
@PostMapping("/courses")
public Course addCourse(@RequestBody Course course)
{
return this.courseService.addCourse(course);
}
@PutMapping("/courses/{courseId}")
public Course updateCourse(@PathVariable String courseId,@RequestBody Course course)
{
return this.courseService.updateCourse(Long.parseLong(courseId),course);
}
@DeleteMapping("/courses/{courseId}")
public List<Course> deleteCourse(@PathVariable String courseId)
{
return (List<Course>) this.courseService.deleteCourse(Long.parseLong(courseId));
}
}
Here is the service implementation of the request :
@Service
public class CourseServiceImpl implements CourseService {
List<Course> list;
public CourseServiceImpl()
{
list = new ArrayList<>();
list.add(new Course(145l,"Java Array","Basic Array"));
list.add(new Course(123l,"Java Constructor","Basic Constructor"));
}
@Override
public List<Course> getCourses() {
return list;
}
@Override
public Course getCourse(long courseId) {
Course c = null;
for(Course course:list)
{
if(course.getId()==courseId)
{
c=course;
break;
}
}
return c;
}
@Override
public Course addCourse(Course course) {
list.add(course);
return course;
}
@Override
public Course updateCourse(long courseId,Course course) {
Course c = null;
for(Course cour:list)
{
if(cour.getId()==courseId)
{
cour.setTitle(course.getTitle());
cour.setDescription(course.getDescription());
c=cour;
}
}
return c;
}
@Override
public List<Course> deleteCourse(long courseId) {
for(Course course:list)
{
if(course.getId()==courseId)
{
list.remove(course);
}
}
return list;
}
}
No errors in spring boot.
Error I got in postman is here :
{
"timestamp": "2021-07-13T03:36:27.454+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/courses/786"
}
Solution
According to your Code, foreach cannot used to remove item, you should use Iterator.
for (Iterator<Course> iterator = list.iterator(); iterator.hasNext(); ) {
Course course = iterator.next();
if (course.getId() == courseId) {
iterator.remove();
}
}
Answered By - Daiql