Dan
Dan

Reputation: 2100

Missing request param when it is included in body

I am posting a POJO where I get an error saying the field is not included.

Asset POJO

public class Asset {

    private MultipartFile[] files;
    private String name;
    private String meta;

    //Constructor/Getters n Setters
}

Resource Method

@PostMapping("asset")
public ResponseEntity uploadAsset(@RequestParam("asset") Asset asset) {
    System.out.println(asset);
    return new ResponseEntity(HttpStatus.ACCEPTED);
}

PostMan JSON Body

{
    "asset" : {
        "files": [
            "@/home/Downloads/1.jpeg",
            "@/home/Downloads/2.jpeg"   
        ],
        "name": "assetName",
        "meta": "assetMeta"
    }
}

PostMan JSON Response

{
    "timestamp": "2019-10-29T20:46:19.536+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Required Asset parameter 'asset' is not present",
    "path": "/asset"
}

I don't understand why I get the Required Asset parameter 'asset' is not present message when I have it in the JSON body. Any ideas on this?

Upvotes: 0

Views: 1608

Answers (4)

Dan
Dan

Reputation: 2100

I tried @Jordans answer and the endpoint was called with all values set to null :(

Doing more research I came across this statement https://stackoverflow.com/a/51982230/2199102 and tried it out.

Combining @Jordans answer and then the annotation change, I was able to get the answer I wanted

Upvotes: 0

0gam
0gam

Reputation: 1423

RequestParam

Annotation which indicates that a method parameter should be bound to a web request parameter.

RequestBody

Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.

HttpMessageConverter

Strategy interface that specifies a converter that can convert from and to HTTP requests and responses.

You need to check converter dependency. because you using application/json.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>

Q : Missing request param when it is included in body

A : Use @RequestBody annotation.

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

Use @RequestBody rather than @RequestParam

public ResponseEntity uploadAsset(@RequestBody Asset asset) {

Upvotes: 1

Jordan
Jordan

Reputation: 2283

Based on your payload, Spring is expecting an object that looks like this:

public class SomeClass {
    private Asset asset;
}

Change your payload to look like this:

{
    "files": [
        "@/home/Downloads/1.jpeg",
        "@/home/Downloads/2.jpeg"   
    ],
    "name": "assetName",
    "meta": "assetMeta"
}

Upvotes: 0

Related Questions