Home > Software engineering >  Query parameters with postman and Spring
Query parameters with postman and Spring

Time:11-28

Can someone explain to me why given this controller:

@RestController
@RequestMapping("/gamification")
public class GamificationController {

    private static final Logger logger = LoggerFactory.getLogger(GamificationController.class);

    @Autowired
    private GameServiceImpl gameService;


    @GetMapping("/retrieve-stats/?user={userId}")
    ResponseEntity<GameStats> getUserStats(@RequestParam("userId") String userId){
        logger.debug("UserId is {}", userId);
        return ResponseEntity.ok(gameService.retrieveStatsForUser(Long.parseLong(userId)));
    }

}

and this pm request

enter image description here

I get a 404 NOT FOUND?

and If I add brackets to the query parameter, I get a 400 BAD REQUEST

enter image description here

CodePudding user response:

You need to remove the /?user={userId} from @GetMapping as well as from the 1st Postman screenshot request and Construct it like the below one.

@GetMapping("/retrieve-stats")
ResponseEntity<GameStats> getUserStats(@RequestParam("userId") String userId){
    logger.debug("UserId is {}", userId);
    return ResponseEntity.ok(gameService.retrieveStatsForUser(Long.parseLong(userId)));
}

PS: And you don't have to cast it Long.parseLong, you can declare the parameter with the type @RequestParam("userId") Long userId, Spring is smart enough to autobox the variable type based on its declartion.

  • Related