I recently tried to program a simple api in spring.
When I try it with postman, the only two working endpoints are the fetchAllMovie
and the createMovie
. The others (with request parameter) give a response:
{
"timestamp": "2021-11-30T14:38:34.396 00:00",
"status": 405,
"error": "Method Not Allowed",
"path": "/api/movies"
}
Here's a snippet:
@RestController
@RequestMapping("/api/movies")
public class MovieController {
@Autowired
private MovieService movieService;
@Autowired
private MovieRepository movieRepository;
@Autowired
private MovieMapper movieMapper;
@GetMapping
public List<Movie> fetchAllMovie() {
return movieService.getAllMovie();
}
@PostMapping
public MovieDto createMovie(@RequestBody MovieCreationDto movieCreationDto) {
Movie movie = movieMapper.creationDtoToModel(movieCreationDto);
return movieMapper.modelToDto(movieRepository.save(movie));
}
@GetMapping("/{movieId}")
public MovieDto fetchMovieById(@PathVariable("movieId") String movieId) throws MovieNotFoundException {
Movie movie = movieRepository.findById(movieId).orElseThrow(MovieNotFoundException::new);
return movieMapper.modelToDto(movie);
}
}
So if I send a GET request like http://localhost:8080/api/movies?movieId=619fa9d9b0c30252474b9a01
I get the error, but if I send a GET or POST request like http://localhost:8080/api/movies
i can get all of the data from the data base or I can POST in it. (Of course with the proper request body)
Note it: Not only the GET req not working. Anything with request parameter gives me this error.
CodePudding user response:
The @PathVariable is used to send parameter in path, like this: http://localhost:8080/api/movies/619fa9d9b0c30252474b9a01
If you want to send it using URL you specified, you need to use annotation @RequestParam
CodePudding user response:
If you are using the @PathVariable as the input parameter, then you should call the endpoint in the following way:
http://localhost:8080/api/movies/619fa9d9b0c30252474b9a01
If you would like to use the @RequestParameter then call the api like this:
http://localhost:8080/api/movies?movieId=619fa9d9b0c30252474b9a01
Quick summary: https://www.baeldung.com/spring-requestparam-vs-pathvariable