Search code examples
spring-bootspring-restcontroller

Got status 500 and message "Missing URI template variable 'rank'", whenever test HTTP POST request on postman


I got the error "Resolved [org.springframework.web.bind.MissingPathVariableException: Missing URI template variable 'rank' for method parameter of type Rank]" on eclipse console And message: "Missing URI template variable 'rank' for method parameter of type Rank" with status "500" whenever try HTTP POST request

  1. My RESTController code:
@RestController
@RequestMapping(path =  "/comp")
public class RankController {
    @PostMapping(path = "/rank")
    ResponseEntity<Rank> createRank(@Valid @PathVariable Rank rank) throws URISyntaxException{
        Rank result = rankRepository.save(rank);
        return ResponseEntity.created(new URI("/comp/rank" + result.getId())).body(result);
    }
}
  1. My Rank entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "RANK_TBL")
public class Rank {

    @Id
    private Long id;
    private String name;

    @ManyToOne(cascade = CascadeType.PERSIST)
    private Employee employee;
}
  1. My Employee entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "EMPLOYEE_TBL")
public class Employee {
    
    @Id
    private Long id;
    private String name;
    private String email;
    
    @OneToMany
    private Set<Rank> Rank;
    
}

Solution

  • Change @PathVariable with @RequestBody

    Here you are making a request to save the entity and you should pass the payload as @RequestBody in JSON format. From postman you may use raw type and select the JSON type.

    Ideal way is to use @RequestBody whenever we are creating or updating the records which requires the object to passed with POST and PUT methods. For methods which retrieves the records based on Id or some parameters you may use @PathVariable

    You may explore more about the annotations here