I have the following entity:
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.index.Indexed
import org.springframework.data.mongodb.core.mapping.Document
import javax.validation.constraints.NotNull
@Document
class Book(
@Id
var id: Int,
@Indexed(unique=true)
@NotNull
var name: String,
@NotNull
var price: Double,
)
and its corresponding Controller with a post method:
import org.springframework.validation.annotation.Validated
import javax.validation.Valid
@RestController
@RequestMapping("/api")
class BookController(val bookRepository: BookRepository) {
@PostMapping("/books")
fun postMovie(@Valid @RequestBody book: Book): ResponseEntity<Int> {
val currentBookEntry = bookRepository.save(book)
return ResponseEntity.status(HttpStatus.CREATED).body(currentBookEntry.id)
}
}
I want to return an HTTP 400 response every time when the request body for post is missing a field. For example: In swagger I'm making a post request with the following body:
{
"name": "Random Book"
}
Since the price is missing, the request should fail. But I'm getting an HTTP 201 response. How can I check if the JSON payload has all the fields completed because neither of @NotNull and @Valid annotations doesn't seem to work.