Wrapper
Wrapper

Reputation: 932

How to write appropriate endpoint in Spring Boot for GET request?

I have an assignment to write simple GET request.

The format that is going to be typed in URL is like this:

http://localhost:8080/api/tasks/20-08-2020

Server should return TODOs for that date. I did managed to write a finder method. But not sure how to write an endpoint. This is what I have so far:

@GetMapping(value = "/{date}", consumes="application/json")
public ResponseEntity<List<Task>> getTasksByDateUsingURL(@PathVariable("date") @DateTimeFormat(pattern="dd-MM-yyyy") @Valid LocalDate dueDate){
    
    List<Task> tasks = taskService.getAllTasksByDate(dueDate);
    return  new ResponseEntity<List<Task>>(tasks,HttpStatus.OK);
}

This is inside RestController class:

@RestController
@RequestMapping(value="/api/tasks")
public class TaskController {...}

I cannot hit this GET endpoint...

Upvotes: 0

Views: 96

Answers (2)

Vladimir Shefer
Vladimir Shefer

Reputation: 739

As author said in comments:

When try to call the endpoint from browser, the mapping is not executed.

Seems like that the browser is sending request with wrong Content-Type header. Your mapping is explicitly requires only application/json value.

When try to call the endpoint from Postman, the application returns 400 status.

I could not see the body of response, but I guess the problem is @Valid annotation on the parameter. How should Spring validate the LocalDate?

So the solution is to remove consumes="application/json" from mapping or send corresponding Content-Type value and remove @Valid annotation from parameter.

Upvotes: 1

Vladimir Shefer
Vladimir Shefer

Reputation: 739

Workaround for your problem is to get the string as parameter and parse it manually

@GetMapping(value = "/{date}", consumes="application/json")
public ResponseEntity<List<Task>> getTasksByDateUsingURL(
    @PathVariable("date") 
    String date
){
    LocalDate dueDate = parse(date);
    List<Task> tasks = taskService.getAllTasksByDate(dueDate);
    return  new ResponseEntity<List<Task>>(tasks,HttpStatus.OK);

}

private LocalDate parse(String stringDate) {
    // TODO
}

Upvotes: 1

Related Questions