snark snark - 1 year ago 209
reST (reStructuredText) Question

How to retrieve an XML string from a POST RequestBody in Swagger-generated Spring server code?

I want to create a REST API method that receives an XML string sent by POST. I'm using Swagger Editor to design my REST API top-down and to generate the server stub code.

The POST method looks like this in my


summary: Store a model.
description: Stores the XML content of the specified model.
- application/xml;charset=UTF-8
- name: model
in: body
description: The model XML you want to store
type: string
required: true
description: Model stored successfully
description: URL of the stored model.
type: string

I also have this global setting in the yaml file:

- application/json

When I use the Swagger Editor's Generate Server > Spring menu option the following interface method is generated for the POST method:

@ApiOperation(value = "Store a model.", notes = "Stores the XML content of the specified model.", response = Void.class, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Model stored successfully", response = Void.class) })
@RequestMapping(value = "/models",
produces = { "application/json" },
consumes = { "application/xml;charset=UTF-8" },
method = RequestMethod.POST)
ResponseEntity<Void> modelsPost(

@ApiParam(value = "The model XML you want to store" ,required=true ) @RequestBody String model);

and this is the corresponding stub implementation:

public ResponseEntity<Void> modelsPost(
@ApiParam(value = "The model XML you want to store" ,required=true ) @RequestBody String model

) {
// do some magic!
return new ResponseEntity<Void>(HttpStatus.OK);

I use Postman to post some dummy XML to the method on my running Springboot service:

Postman screenshot

But when I print out the value of
inside the implementation method with
log.debug("Model XML = " + model);
I get output like this in the logs:

Model XML = ------WebKitFormBoundaryA3o70hOgLFoLLBoY
Content-Disposition: form-data; name="model"

<?xml version="1.0" encoding="utf-8"?><Hello></Hello>

How do I get just the XML itself into the value of
? I want it to be this instead in this example:

<?xml version="1.0" encoding="utf-8"?><Hello></Hello>

Remember I can't just edit the Java method signatures directly because the Swagger Editor is generating them. If my swagger definition is wrong what should I be using instead to post an XML string?

The XML in practice is likely to be large so sending it as a request parameter is not an option. I'm also not going to process the XML so it's ok to treat it as a string.

Answer Source

In postman, switch from form-data to raw, and select the relevant content-type (application/xml).

You have to do this because spring is expecting your object to be in the request body (because of @RequestBody annotation on your parameter)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download