简体   繁体   中英

Spring API REST Controller returning HTTP 406 instead of HTTP 201 after POST method

I am building and testing a simple Spring Boot API REST tutorial. I have faced with an issue that I am trying to understand. I am getting an HTTP 406 (NOT ACCEPTABLE) when calling POST method to create and persist a new entity.

Problem is the entity is persisted but the response to the client is not what should be expected (HTTP 201 CREATED with URI in this case).

Tutorial and TutorialDto classes have the exact same attributes. Here is the definition:

public class TutorialDto {
    private long id;
    private String title;
    private String description;
    private boolean published;

...
}

Here is my POST method in @RestController class:

@PostMapping("/tutorial")
public ResponseEntity.BodyBuilder createTutorial(@RequestBody final TutorialDto tutorialDto) {
    final TutorialDto createdTutorial = tutorialService.add(tutorialDto);
    return ResponseEntity.created(URI.create(String.format("tutorial/%d", createdTutorial.getId())));
}

And here is the @Service method to create the entity:

@Transactional
public TutorialDto add(final TutorialDto tutorialDto) {
    final Tutorial createdTutorial = tutorialRepository.save(modelmapper.map(tutorialDto, Tutorial.class));
    return Optional.of(modelmapper.map(createdTutorial, TutorialDto.class))
            .orElseThrow(() -> new TutorialCreationException(
                    String.format("Tutorial: %s could not be created", tutorialDto.getTitle()))
            );
}

This is the request body:

{
    "title": "tutorial",
    "description": "This is the first created tutorial"
}

And this is the response body:

{
    "timestamp": "2022-04-16T00:40:36.626+00:00",
    "status": 406,
    "error": "Not Acceptable",
    "path": "/api/v1/tutorial"
}

I am getting the HTTP 406 response at the end of the controller method, after returning the "ResponseEntity.created".

Thanks in advance.

Looks like you are using wrong usage of ResponseEntity.BodyBuilder. Here is an example

Hence, your controller code should look something like this:

@PostMapping("/tutorial")
public ResponseEntity createTutorial(@RequestBody final TutorialDto tutorialDto) {
    final TutorialDto createdTutorial = tutorialService.add(tutorialDto);
    return ResponseEntity.created(URI.create(String.format("tutorial/%d", createdTutorial.getId()))).body(createdTutorial);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM