Search code examples
javaspring-bootpostmanspring-restcontroller

Bad Request while doing POST on Postman using SpringBoot


I am getting Bad Request when trying to do POST to createCategory end point. All endpoint works but not for createCategory. Am i doing something wrong?

All my DTO classes using the same annotation but only this one doesn't work. Is it possible that spring doesn't accept single variable response body?

endpoint: http://localhost:8180/api/v1/categories

request body in json:
{
   "name": "Category 1"
}

CategoryController:

    @RestController
    @RequiredArgsConstructor
    @RequestMapping("api/v1/categories")
    public class CategoryController {

    private final CategoryApplicationService categoryApplicationService;

    @PostMapping
    public ResponseEntity<Data<CategoryIDResponse>> createCategory(@RequestBody CreateCategory createCategory){
        return new ResponseEntity<>(new Data<>(categoryApplicationService.createCategory(createCategory)), HttpStatus.CREATED);
    }

    @PatchMapping
    public ResponseEntity<Data<CategoryIDResponse>> updateCategory(@RequestBody UpdateCategory updateCategory){
        return new ResponseEntity<>(new Data<>(categoryApplicationService.updateCategory(updateCategory)), HttpStatus.OK);
    }

    @DeleteMapping("/{categoryID}")
    public ResponseEntity<Data<CategoryIDResponse>> deleteCategory(@PathVariable("categoryID") UUID categoryID){
        return new ResponseEntity<>(new Data<>(categoryApplicationService.deleteCategory(categoryID)), HttpStatus.OK);
    }

    @GetMapping("/{categoryID}")
    public ResponseEntity<Data<GetCategoryResponse>> getCategory(@PathVariable("categoryID") UUID categoryID){
        return new ResponseEntity<>(new Data<>(categoryApplicationService.getCategory(categoryID)), HttpStatus.OK);
    }

    @GetMapping
    public ResponseEntity<Data<List<GetCategoryResponse>>> getAllCategory(){
        return new ResponseEntity<>(new Data<>(categoryApplicationService.getAllCategory()), HttpStatus.OK);
    }
}

DTO:

CreateCategory:

    @Getter
    @Builder
    @AllArgsConstructor
    public class CreateCategory {

    @NotNull
    private final String name;
}

Solution

  • This is happening because you have not added NoArgsConstructor in your DTO.

    @Getter
    @Setter
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public class CreateCategory {
       private String name;
    }
    

    Change your DTO to above code. Working fine for me.

    Hope this helps.