awkwardalex
awkwardalex

Reputation: 1

How to override Swagger's default produces header value?

I am using Swagger version 2.4.0 and Spring Boot 2.0.4.RELEASE and have an application with several API endpoints and with default Swagger configuration having default produces header value set to application/json.

SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES = ImmutableSet.of(
            "application/json"
    );

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .produces(DEFAULT_PRODUCES_AND_CONSUMES)
                .consumes(DEFAULT_PRODUCES_AND_CONSUMES);
    }
}

And with API endpoint set up being.

ApiEndpoint.java

@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "/transform", protocols = "http, https")
@RequestMapping(value = "/transform")
public interface ApiEndpoint {

    @POST
    @RequestMapping(value = "/text", method = RequestMethod.POST)
    @ApiOperation(value = "Transform to plain text", produces = MediaType.TEXT_PLAIN)
    @CrossOrigin
    String transformToText(@RequestBody TransformRequest transformRequest) throws Exception;
}

Now I want this endpoint to produce response with content type being only plain text, but SwaggerConfig adds application/json option as default one. So in order to correctly use this endpoint I would need to change Response Content Type from application/json to text/plain every time, which would get annoying pretty quick considering that this endpoint is used for testing. Is there a way to override SwaggerConfig or to add a parameter so text/plain is the only option or at least to set the text/plain as the default option only for this one endpoint?

Upvotes: 0

Views: 3451

Answers (2)

Lucas Silva
Lucas Silva

Reputation: 11

just specifying type in order in the endpoint annotation, example:

atribute produces receive an array, so you can put more than one type

@PostMapping(value = "/text", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE })

I advise removing produces in @Bean, as its API contains endpoint that did not always follow the standard idea of "application/json"

Upvotes: 0

ASK
ASK

Reputation: 1274

you just have to define the response content type in your requestMapping annotation.

That is,

 @RequestMapping(value = "/text", method = RequestMethod.POST)

will be replaced by,

 @RequestMapping(value = "/text", method = RequestMethod.POST, produces="text/plain")

Means, you have to define in requestMapping that what type of content this mapping will going to return.

Note : Will be good practice if you use

@PostMapping(value = "/text", produces="text/plain")

Hope, the solution will work fine.

Upvotes: 0

Related Questions