Swagger - Issue using @ApiParam with @CookieParam

2.7k views Asked by At

I'm using Swagger 1.3.10 and am trying to get the Swagger UI to functionally accept a cookie parameter for a REST service. Here's an example of my Java code:

    public Response getUserInfo(
    @Context HttpHeaders headers, 
    @ApiParam(value="Enter brand code as an Integer", defaultValue="101", required=true) @CookieParam(value = "userBrand") String brand)

Now the actual Swagger UI renders just fine actually...it even populates the default value with "101" in this case. The problem is when I click "Try it Out" the brand parameter is always coming through as null.

Seems like I'm missing something simple here...any thoughts?

Thanks a lot!

2

There are 2 answers

2
Ron On BEST ANSWER

Cookie parameters are not really supported by Swagger. Swagger-core generates them as cookie parameters, but they are not supported by the other tools as that's not an official part of the spec.

0
saran3h On

Cookie parameters are not supported out of the box. Instead, you need to write your own handler for that. See here:

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CookieValue;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ParameterBuilderPlugin;
import springfox.documentation.spi.service.contexts.ParameterContext;

import java.lang.annotation.Annotation;
import java.util.List;

import static springfox.documentation.swagger.common.SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER;
import static springfox.documentation.swagger.common.SwaggerPluginSupport.pluginDoesApply;

/*
 * Custom swagger configuration to support Cookies in requests
 *
 * Created by Saransh Bansal on 11/03/2021, 13:02
 */
@Component
@Order(SWAGGER_PLUGIN_ORDER + 1000)
public class SwaggerCustomParameterBuilderPlugin implements ParameterBuilderPlugin {

    @Override
    public void apply(ParameterContext context) {
        if (isCookieValue(context)) {
            context.parameterBuilder().parameterType("cookie");
        }
    }

    private boolean isCookieValue(ParameterContext context) {
        List<Annotation> annotations = context.resolvedMethodParameter().getAnnotations();
        return annotations.stream().anyMatch(annotation -> annotation.annotationType() == CookieValue.class);
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return pluginDoesApply(documentationType);
    }
}

Code provided by: https://github.com/mwinteringham