How to accept json, xml, x-www-form-urlencoded in openapi driven spring boot application?

1.2k views Asked by At

I'm implementing a petstore server in spring using the gradle plugin to generate classes for the API: https://github.com/swagger-api/swagger-petstore/blob/swagger-petstore-v3-1.0.5/src/main/resources/openapi.yaml

An example for such a generated API code is

...
public interface UserApi {
    ...
    @PostMapping(
        value = "/user",
        produces = { "application/json", "application/xml" },
        consumes = { "application/json", "application/xml", "application/x-www-form-urlencoded" }
    )
    default ResponseEntity<User> createUser(@ApiParam(value = "Created user object"  )  @Valid @RequestBody(required = false) User user) {
    ....

For a minimal example I don't even overwrite the above method.

With springdoc I can create a swagger ui page at http://localhost:8080/swagger-ui.html that is generated from the code. There, I can generate curl requests for all media types offered y the api:

curl -X POST "http://localhost:8080/user" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{\"id\":0,\"username\":\"string\",\"firstName\":\"string\",\"lastName\":\"string\",\"email\":\"string\",\"password\":\"string\",\"phone\":\"string\",\"userStatus\":0}"
curl -X POST "http://localhost:8080/user" -H  "accept: application/json" -H  "Content-Type: application/xml" -d "<?xml version=\"1.0\" encoding=\"UTF-8\"?><User>\t<id>0</id>\t<username>string</username>\t<firstName>string</firstName>\t<lastName>string</lastName>\t<email>string</email>\t<password>string</password>\t<phone>string</phone>\t<userStatus>0</userStatus></User>"
curl -X POST "http://localhost:8080/user" -H  "accept: application/json" -H  "Content-Type: application/x-www-form-urlencoded" -d "id=0&username=string&firstName=string&lastName=string&email=string&password=string&phone=string&userStatus=0"

The first(json) works, but for xml and x-www-form-urlencoded I get:

{"timestamp":"2020-10-19T22:42:43.215+00:00","status":415,"error":"Unsupported Media Type","message":"","path":"/user"}

That response code is not in the generated default implementation, it must be thrown in the steps before.

There are similar questions already on stackoverflow, but through openapi I cannot just leave out annotations. Is there a way for me to implement a request accepting all three media types using openapi and spring boot?

0

There are 0 answers