简体   繁体   中英

Swagger Spring mvc reponsebody

Is there a way to present the request body of a complex object in swagger with each field having it's input?

In simple words if one of my apis expects a Person (suppose it has just a firstname/lastname) as @RequestBody then the only way to provide this Person with swagger would be to give the entire json of Person. Is there a way to enable each separate field to have it's separate input for firstname/lastname for example?

If you annotate your Operation using @ModelAttribute it should do exactly what you're looking for

For eg instead of

public void updatePersonName(@RequestBody Person person) { ... }

Use this

public void updatePersonName(@ModelAttribute Person person) { ... }

The @ModelAttribute will expand the primitive properties and provide fields for entering in the first name and last name in the swagger ui. The equivalent of that operation is

public void updatePersonName(@RequestParam String firstName, 
                             @RequestParam String lastName) { ... }

I'm also using swagger with the default swagger UI and I don't think it's possible unless you change the swagger UI code. But a quite convenient solution is to define the type of your parameter and then provide the model for that type. For instance

 "parameters": [
                {
                    "in": "body",
                    "name": "body",
                    "description": "A Person",
                    "required": true,
                    "type": "Person"
                }
            ]

And then

 "definitions": {
    "Person": {
      "properties": {
            "firstName": {
                "type": "string"
            },
            "lastName": {
                "type": "string"
            }
        }
      }
   }

This way the model appears in the UI and you can easily copy it to the request body textbox and fill it with content manually.

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