Swagger overwrites methods with the same path and method but different parameters - spring-boot

Swagger overwrites methods with the same path and method but different parameters
I have an application with Spring Boot 2.3.5.RELEASE, webflux and springfox 3.0.0. I have developed two GET methods with the same path but different parameters, one does not receive parameters and returns a list and others for findAll.
The case is that Swagger only generates the documentation of one of the methods, sometimes the listing, others the paging. How can I tell swagger that they are different methods and document both for me?
My Controller code:
#GetMapping(value = "/foo", params = {"page", "size"})
#ResponseBody
public Mono<ResponseEntity<Mono<Page<FooDTO>>>> findByFilter(FooFilterDTO filter,
#SortDefault(sort = "id", direction = Sort.Direction.DESC) #PageableDefault(value = 10) Pageable pageable) {
//...
}
#GetMapping(value = "/foo")
#ResponseBody
public Mono<ResponseEntity<Flux<FooDTO>>> findAll() {
//...
}
My Swagger configuration:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Value("${app.version}")
private String version;
#Bean
public Docket docketUsersV1() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.fooApiInfo())
.enable(true)
.groupName("foo-api")
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Arrays.asList(apiKey()))
.select()
.paths(fooPaths())
.build();
}
private ApiInfo fooApiInfo() {
return new ApiInfoBuilder()
.title("Reactive Foo")
.description("Reactive API")
.version(appVersion)
.build();
}
private Predicate<String> fooPaths() {
return regex("/foo.*");
}
}

As far as I know, you can only define one API path by each HTTP verb (GET, POST...), independently of the optional parameters the API consumer sends.
My advice would be to define a single GET /foo path, with optional parameters page & size (ie. not required)
Then I would have a single entrypoint function in the controller, then redirect to each findByFilter private method or findAll private method depending on whether page & size are defined or not.

Related

How I can ignore PathVariable conditionally on swagger ui using springdoc openapi

I am migrating from springfox 2.9.0 to springdoc-openapi-ui 1.2.33.
I have a requirement to show or hide the PathVariable on swagger ui based on condition.
I have two paths like below
String nameIdentifier = "{fisrtName}/{lastName}"
String nameIdentifier = "{fisrtName}"
I am passing one of the above nameIdentifier based on the requirement.
I am using a single controller for the above paths as shown below
#GetMapping(path = "persons/${nameIdentifier}/display")
public List<Person> getPersons(#PathVariable String fisrtName,
#IgnoreLastName #PathVariable Optional<String> lastName) {
}
In springfox I was able to achieve it using docket.ignoredParameterTypes(IgnoreLastName.class) as shown below.
#Bean
public Docket api() {
Docket docket;
docket = new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("go.controller")).paths(PathSelectors.any()).build()
.apiInfo(apiInfo());
if (!nameIdentifier.contains("lastName")) {
docket.ignoredParameterTypes(IgnoreLastName.class);
}
return docket;
}
But in springdoc open api I am unable to achieve the same.
Your help appreciated in the same.
Coding is done in java
Thanks
You can use #Hidden swagger annotations or #Parameter(hidden = true).
If you can not pass on parameter level, you can set it globally: You will need to upgrade to v1.3.0 of springdoc-openapi-ui.
static {
SpringDocUtils.getConfig().addAnnotationsToIgnore(IgnoreLastName.class);
}

Keep same URL but contract changes in Spring Boot REST Open API 3?

I am using Spring Boot and REST and Open API 3 implementation. In this example, v1 Group has List implementation - all data will get in List, in v2 Group has pagination implementation - all data will come in the form of pages.
For the consumer, we don't want to change endpoint url for them to be consume.
Endpoint which returns list.
#GetMapping(value = "/contacts", headers = {"Accept-version=v1"})
public ResponseEntity<List<Contact>> findAll() {
List<Contact> contacts = contactService.findContactList();
return new ResponseEntity<>(contacts, HttpStatus.OK);
}
Endpoint with Pagination
#GetMapping(value = "/contacts", headers = {"Accept-version=v2"})
public ResponseEntity<List<Contact>> findAll(Pageable pageable) {
Page<Contact> contactPages = contactService.findContactPageable(pageable);
return new ResponseEntity<>(contactPages, HttpStatus.OK);
}
I want V1 endpoint to be shown in GroupedOpenApi and v2 endpoint to be shown in the GroupedOpenApi2. Any suggestions ?
Lets assume you put the two endpoints in different packaged and then use the Following GroupedOpenApi definition:
#Bean
public GroupedOpenApi groupOpenApiV1() {
return GroupedOpenApi.builder()
.setGroup("v1")
.packagesToScan("test.org.springdoc.api.v1")
.build();
}
#Bean
public GroupedOpenApi groupOpenApiV2() {
return GroupedOpenApi.builder()
.setGroup("v2")
.packagesToScan("test.org.springdoc.api.v2")
.build();
}

Rest API version header in SwaggerUI

I want to use Springfox SwaggerUI for my Rest API (spring-mvc) documentation.
I use version header in #RequestMapping annotation, but if I have two versions of same method, in SwaggerUI I can see only one.
For example:
#GetMapping(value = "/users", headers = "X-API-VERSION=1")
public List<User> getUsersV1(){...}
#GetMapping(value = "/users", headers = "X-API-VERSION=2")
public List<User> getUsersV2(){...}
Above code results in only one method visible in api documentation.
Is there any option to configure Swagger to differ endpoints with consideration of my version header?
After some research I have found solution to my problem, maybe it will help someone in the future. I add "#v" suffix to path using PathDecorator.
Now I can see all my methods in generated documentation.
#Component
#Order(value = Ordered.HIGHEST_PRECEDENCE + 70)
public class VersionPathDecorator implements PathDecorator {
private final static Logger logger = LoggerFactory.getLogger(VersionPathDecorator.class);
#Override
public Function<String, String> decorator(PathContext context) {
return (path) -> {
StringBuilder sb = new StringBuilder(path);
Field parent = null;
try {
parent = PathContext.class.getDeclaredField("parent");
parent.setAccessible(true);
RequestMappingContext rmc = (RequestMappingContext) parent.get(context);
rmc.headers()
.stream()
.filter(h -> RequestHeader.X_API_VERSION.headerName.equals(h.getName()))
.map(NameValueExpression::getValue)
.findFirst()
.ifPresent(v -> sb.append("#v").append(v));
} catch (NoSuchFieldException | IllegalAccessException e) {
logger.error("path decoration failed", e);
}
return sb.toString();
};
}
#Override
public boolean supports(DocumentationContext documentationContext) {
return true;
}
}
Swagger identifies services by its endpoint.
Each feature must respond to a different endpoint, and headers for that function should not be used.
If you are using REST services read a bit about Restfull and follow its principles. This url can help you: http://docs.oracle.com/javaee/6/tutorial/doc/gijqy.html

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for #RequestBody MultiValueMap

Based on the answer for problem with x-www-form-urlencoded with Spring #Controller
I have written the below #Controller method
#RequestMapping(value = "/{email}/authenticate", method = RequestMethod.POST
, produces = {"application/json", "application/xml"}
, consumes = {"application/x-www-form-urlencoded"}
)
public
#ResponseBody
Representation authenticate(#PathVariable("email") String anEmailAddress,
#RequestBody MultiValueMap paramMap)
throws Exception {
if(paramMap == null || paramMap.get("password") == null) {
throw new IllegalArgumentException("Password not provided");
}
}
the request to which fails with the below error
{
"timestamp": 1447911866786,
"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported",
"path": "/users/usermail%40gmail.com/authenticate"
}
[PS: Jersey was far more friendly, but couldn't use it now given the practical restrictions here]
The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this
we must remove the #RequestBody annotation.
Then try the following:
#RequestMapping(
path = "/{email}/authenticate",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {
MediaType.APPLICATION_ATOM_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE
})
public #ResponseBody Representation authenticate(
#PathVariable("email") String anEmailAddress,
MultiValueMap paramMap) throws Exception {
if (paramMap == null &&
paramMap.get("password") == null) {
throw new IllegalArgumentException("Password not provided");
}
return null;
}
Note that removed the annotation #RequestBody
answer: Http Post request with content type application/x-www-form-urlencoded not working in Spring
It seems that now you can just mark the method parameter with #RequestParam and it will do the job for you.
#PostMapping( "some/request/path" )
public void someControllerMethod( #RequestParam Map<String, String> body ) {
//work with Map
}
Add a header to your request to set content type to application/json
curl -H 'Content-Type: application/json' -s -XPOST http://your.domain.com/ -d YOUR_JSON_BODY
this way spring knows how to parse the content.
In Spring 5
#PostMapping( "some/request/path" )
public void someControllerMethod( #RequestParam MultiValueMap body ) {
// import org.springframework.util.MultiValueMap;
String datax = (String) body .getFirst("datax");
}
#RequestBody MultiValueMap paramMap
in here Remove the #RequestBody Annotaion
#RequestMapping(value = "/signin",method = RequestMethod.POST)
public String createAccount(#RequestBody LogingData user){
logingService.save(user);
return "login";
}
#RequestMapping(value = "/signin",method = RequestMethod.POST)
public String createAccount( LogingData user){
logingService.save(user);
return "login";
}
like that
Simply removing #RequestBody annotation solves the problem (tested on Spring Boot 2):
#RestController
public class MyController {
#PostMapping
public void method(#Valid RequestDto dto) {
// method body ...
}
}
I met the same problem when I want to process my simple HTML form submission (without using thymeleaf or Spring's form tag) in Spring MVC.
The answer of Douglas Ribeiro will work very well. But just in case, for anyone, like me, who really want to use "#RequestBody" in Spring MVC.
Here is the cause of the problem:
Spring need to ① recognize the "Content-Type", and ② convert the
content to the parameter type we declared in the method's signature.
The 'application/x-www-form-urlencoded' is not supported, because, by
default, the Spring cannot find a proper HttpMessageConverter to do
the converting job, which is step ②.
Solution:
We manually add a proper HttpMessageConverter into the Spring's
configuration of our application.
Steps:
Choose the HttpMessageConverter's class we want to use. For
'application/x-www-form-urlencoded', we can choose
"org.springframework.http.converter.FormHttpMessageConverter".
Add the FormHttpMessageConverter object to Spring's configuration,
by calling the "public void
configureMessageConverters(List<HttpMessageConverter<?>>
converters)" method of the "WebMvcConfigurer" implementation class
in our application. Inside the method, we can add any
HttpMessageConverter object as needed, by using "converters.add()".
By the way, the reason why we can access the value by using "#RequestParam" is:
According to Servlet Specification (Section 3.1.1):
The following are the conditions that must be met before post form
data will be populated to the parameter set: The request is an HTTP
or HTTPS request. 2. The HTTP method is POST. 3. The content type is
application/x-www-form-urlencoded. 4. The servlet has made an initial
call of any of the getParameter family of methods on the request
object.
So, the value in request body will be populated to parameters. But in Spring, you can still access RequestBody, even you can use #RequstBody and #RequestParam at the same method's signature.
Like:
#RequestMapping(method = RequestMethod.POST, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public String processForm(#RequestParam Map<String, String> inputValue, #RequestBody MultiValueMap<String, List<String>> formInfo) {
......
......
}
The inputValue and formInfo contains the same data, excpet for the type for "#RequestParam" is Map, while for "#RequestBody" is MultiValueMap.
I wrote about an alternative in this StackOverflow answer.
There I wrote step by step, explaining with code. The short way:
First: write an object
Second: create a converter to mapping the model extending the AbstractHttpMessageConverter
Third: tell to spring use this converter implementing a WebMvcConfigurer.class overriding the configureMessageConverters method
Fourth and final: using this implementation setting in the mapping inside your controller the consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE and #RequestBody in front of your object.
I'm using spring boot 2.
#PostMapping(path = "/my/endpoint", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public ResponseEntity<Void> handleBrowserSubmissions(MyDTO dto) throws Exception {
...
}
That way works for me
You can try to turn support on in spring's converter
#EnableWebMvc
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// add converter suport Content-Type: 'application/x-www-form-urlencoded'
converters.stream()
.filter(AllEncompassingFormHttpMessageConverter.class::isInstance)
.map(AllEncompassingFormHttpMessageConverter.class::cast)
.findFirst()
.ifPresent(converter -> converter.addSupportedMediaTypes(MediaType.APPLICATION_FORM_URLENCODED_VALUE));
}
}
Just add an HTTP Header Manager if you are testing using JMeter :

When use ResponseEntity<T> and #RestController for Spring RESTful applications

I am working with Spring Framework 4.0.7, together with MVC and Rest
I can work in peace with:
#Controller
ResponseEntity<T>
For example:
#Controller
#RequestMapping("/person")
#Profile("responseentity")
public class PersonRestResponseEntityController {
With the method (just to create)
#RequestMapping(value="/", method=RequestMethod.POST)
public ResponseEntity<Void> createPerson(#RequestBody Person person, UriComponentsBuilder ucb){
logger.info("PersonRestResponseEntityController - createPerson");
if(person==null)
logger.error("person is null!!!");
else
logger.info("{}", person.toString());
personMapRepository.savePerson(person);
HttpHeaders headers = new HttpHeaders();
headers.add("1", "uno");
//http://localhost:8080/spring-utility/person/1
headers.setLocation(ucb.path("/person/{id}").buildAndExpand(person.getId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
to return something
#RequestMapping(value="/{id}", method=RequestMethod.GET)
public ResponseEntity<Person> getPerson(#PathVariable Integer id){
logger.info("PersonRestResponseEntityController - getPerson - id: {}", id);
Person person = personMapRepository.findPerson(id);
return new ResponseEntity<>(person, HttpStatus.FOUND);
}
Works fine
I can do the same with:
#RestController (I know it is the same than #Controller + #ResponseBody)
#ResponseStatus
For example:
#RestController
#RequestMapping("/person")
#Profile("restcontroller")
public class PersonRestController {
With the method (just to create)
#RequestMapping(value="/", method=RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public void createPerson(#RequestBody Person person, HttpServletRequest request, HttpServletResponse response){
logger.info("PersonRestController - createPerson");
if(person==null)
logger.error("person is null!!!");
else
logger.info("{}", person.toString());
personMapRepository.savePerson(person);
response.setHeader("1", "uno");
//http://localhost:8080/spring-utility/person/1
response.setHeader("Location", request.getRequestURL().append(person.getId()).toString());
}
to return something
#RequestMapping(value="/{id}", method=RequestMethod.GET)
#ResponseStatus(HttpStatus.FOUND)
public Person getPerson(#PathVariable Integer id){
logger.info("PersonRestController - getPerson - id: {}", id);
Person person = personMapRepository.findPerson(id);
return person;
}
My questions are:
when for a solid reason or specific scenario one option must be used mandatorily over the other
If (1) does not matter, what approach is suggested and why.
ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.
#ResponseBody is a marker for the HTTP response body and #ResponseStatus declares the status code of the HTTP response.
#ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse.
Basically, ResponseEntity lets you do more.
To complete the answer from Sotorios Delimanolis.
It's true that ResponseEntity gives you more flexibility but in most cases you won't need it and you'll end up with these ResponseEntity everywhere in your controller thus making it difficult to read and understand.
If you want to handle special cases like errors (Not Found, Conflict, etc.), you can add a HandlerExceptionResolver to your Spring configuration. So in your code, you just throw a specific exception (NotFoundException for instance) and decide what to do in your Handler (setting the HTTP status to 404), making the Controller code more clear.
According to official documentation: Creating REST Controllers with the #RestController annotation
#RestController is a stereotype annotation that combines #ResponseBody
and #Controller. More than that, it gives more meaning to your
Controller and also may carry additional semantics in future releases
of the framework.
It seems that it's best to use #RestController for clarity, but you can also combine it with ResponseEntity for flexibility when needed (According to official tutorial and the code here and my question to confirm that).
For example:
#RestController
public class MyController {
#GetMapping(path = "/test")
#ResponseStatus(HttpStatus.OK)
public User test() {
User user = new User();
user.setName("Name 1");
return user;
}
}
is the same as:
#RestController
public class MyController {
#GetMapping(path = "/test")
public ResponseEntity<User> test() {
User user = new User();
user.setName("Name 1");
HttpHeaders responseHeaders = new HttpHeaders();
// ...
return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
}
}
This way, you can define ResponseEntity only when needed.
Update
You can use this:
return ResponseEntity.ok().headers(responseHeaders).body(user);
A proper REST API should have below components in response
Status Code
Response Body
Location to the resource which was altered(for example, if a resource was created, client would be interested to know the url of that location)
The main purpose of ResponseEntity was to provide the option 3, rest options could be achieved without ResponseEntity.
So if you want to provide the location of resource then using ResponseEntity would be better else it can be avoided.
Consider an example where a API is modified to provide all the options mentioned
// Step 1 - Without any options provided
#RequestMapping(value="/{id}", method=RequestMethod.GET)
public #ResponseBody Spittle spittleById(#PathVariable long id) {
return spittleRepository.findOne(id);
}
// Step 2- We need to handle exception scenarios, as step 1 only caters happy path.
#ExceptionHandler(SpittleNotFoundException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
public Error spittleNotFound(SpittleNotFoundException e) {
long spittleId = e.getSpittleId();
return new Error(4, "Spittle [" + spittleId + "] not found");
}
// Step 3 - Now we will alter the service method, **if you want to provide location**
#RequestMapping(
method=RequestMethod.POST
consumes="application/json")
public ResponseEntity<Spittle> saveSpittle(
#RequestBody Spittle spittle,
UriComponentsBuilder ucb) {
Spittle spittle = spittleRepository.save(spittle);
HttpHeaders headers = new HttpHeaders();
URI locationUri =
ucb.path("/spittles/")
.path(String.valueOf(spittle.getId()))
.build()
.toUri();
headers.setLocation(locationUri);
ResponseEntity<Spittle> responseEntity =
new ResponseEntity<Spittle>(
spittle, headers, HttpStatus.CREATED)
return responseEntity;
}
// Step4 - If you are not interested to provide the url location, you can omit ResponseEntity and go with
#RequestMapping(
method=RequestMethod.POST
consumes="application/json")
#ResponseStatus(HttpStatus.CREATED)
public Spittle saveSpittle(#RequestBody Spittle spittle) {
return spittleRepository.save(spittle);
}

Resources