Spring Boot swagger file without UI - spring

I have a simple service built in Spring Boot that has a simple API. I've added the springfox libraries to use swagger and the swagger UI, but I do not want my application to serve the UI also. I just want to get the definition from from /api/v1/api-docs
How do I switch off the UI part? Not adding swagger-ui library as a dependency doesn't remove the UI for some reason.

You can block the UI and return HTTP code 404. Something similar to below
#Controller //note - this is a spring-boot controller, not #RestController
public class HomeController {
#RequestMapping ("/swagger/api/v1/api-docs")
public String home(HttpServletRequest request) {
throw new ResourceNotFoundException(); //Custom Solution
or
throw new NoSuchRequestHandlingMethodException(request);
}
}
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
...
}

If you are using Spring Boot
#SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
#Bean
RouterFunction<ServerResponse> routerFunction() {
return route(GET("/swagger"), req ->
ServerResponse.temporaryRedirect("<some 404 page>").build());
}
}

Related

How can I add textbox/textfield in my swagger page built in Spring boot?

I am trying to auto-generate the swagger page for a RestAPI in Spring Boot using annotations.
Code of Controller:
#RestController
#Api(value="UserManagementAPI", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserManagementController {
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
#ApiOperation(value="add a pro",consumes="application/json")
#RequestMapping(value = "/getUser", method = RequestMethod.GET, produces="application/json")
public static List<UserDetails> getUser(#PathVariable(name="id") String id) throws UserException
{
return UserHelper.getUserByEmail(id);
}
Application.java
#SpringBootApplication
#EnableSwagger2
#Configuration
#ComponentScan({ "userManagement"})
#EnableAutoConfiguration
public class Application {
#Bean
public Docket simpleDiffServiceApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("userManagement").apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.any())
// .paths(PathSelectors.any())
// Will also include the basic error controllers by default
.paths(Predicates.not(PathSelectors.regex("/error")))
// Exclude basic error controllers
.build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Business Location Service")
.description("Spring Boot REST APIs for Business Location Service")
.contact(new Contact("EntSol-IoT (Niche Technology Delivery Group)", "http://somewebsite.com",
"some#mail.com"))
.version("1.0").build();
}
In the swagger page, I can see all my APIs. But there are more. It is showing all possible method type (e.g POST, GET, PUT etc.) though in Controller I only wrote GET method.
Another issue is that there is no Textbox in the swagger page under the API where I can search for the id. May be I am missing something. I have been trying to resolve it for past two days. But couldn't help myself. Thanks in advance.
I got the problem. Your getUser method is declared as static. Please remove static, for it to work.
public List<UserDetails> getUser(#PathVariable(name="id") String id) throws UserException { }

#RequestMapping not working in Spring Boot

Controller class.
#RestController
#RequestMapping("/check")
public class Controller {
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
Application class
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
Added all the necessary dependency when running the application shows the
http://localhost:8081/demo/
Hello World
of index.xml
When I change to http://localhost:8081/check/ it gives
HTTP Status 404 – Not Found
Type Status Report
Message /check
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
How can I understand the flow of Spring Boot application?
You need to put the Http method on your method, here I am assuming you are doing a GET request
#RestController
#RequestMapping("/check")
public class Controller {
#GetMapping // you forgot to put http method here
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
Note: GetMapping is only available if you are using Spring 4.3 or above else use #RequestMapping(value = "/url", method = RequestMethod.GET)
Your controller should be like this:
#RestController
public class Controller {
#RequestMapping(value="/check")
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
}
It seems
#RequestMapping(value="/check") is not working.
switch to
#RequestMapping(path="/check")
though as per documentation it should work.

How to get a respose from a localhost url exactly http://localhost:8888/

I have two projects setting up Springboot in it, now, I am going to run these two springboot on eclipse, I set up the port 8888 for projectB.
Here is my projectB controller with RequestMapping.
#RequestMapping(value = "test", method = RequestMethod.GET)
public #ResponseBody String test() {
return "testtesttest";
}
I need to call a url from jquery method that url is to read the respose from a controller in projectB.
how can I call this url ??
I tried "http://localhost:8888/test" and "http://127.0.0.1:8888/test"
but I did not get anything from the response.
The error shows up as :
please give me the solution for this
very appreciated.
Add below code in your application's main class. This configures your web mvc cors mapping to allow request from " * "
#SpringBootApplication
public class Application {
#Configuration
public class MyConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
logger.info("Added CORS config");
registry.addMapping("/**").allowedOrigins("*").maxAge(3600);
}
};
}
}
}

Spring Boot url mappings order for controllers and static pages

I have a Spring Boot web application which is meant to serve both static and controller based (ModelAndView) pages. Problem is that a controller can serve something like /{string} and a static page must be served with /test.
The problem is that the controller mapping takes precedence, and I need to avoid that. If the user hits /test, he must be forwarded to the test.html static page.
I tried to use the order property of ViewControllerRegistry in this way, with no success:
#Configuration
public class MyWebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("forward:/test.html");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE); // but I tried with 0 and -1 as well: annotated controllers should have order equals to 0
}
}
This is my SpringBootApplication class:
#SpringBootApplication
public class VipApplication {
public static void main(String[] args) {
SpringApplication.run(VipApplication.class, args);
}
}
And this is the controller code:
#Controller
public class VipController {
#RequestMapping(value = "/{string}")
public ModelAndView vip(#PathVariable("string") String string) {
ModelAndView mv = new ModelAndView("mypage");
return mv;
}
}
How can I reorder the mappings to make sure static pages are considered before annotated controllers?
(I'm not sure, but) I suggest to override WebMvcConfigurerAdapter.addResourceHandlers() method and configure order of resource handler by invoking ResourceHandlerRegistry.setOrder()

How to configure Spring Data REST to return the representation of the resource created for a POST request?

I am following the spring-data-rest guide Accessing JPA Data with REST. When I http post a new record it is inserted (and the response is a 201). That is great, but is there a way to configure the REST MVC code to return the newly created object? I'd rather not have to send a search request to find the new instance.
You don't have to search for the created entity. As the HTTP spec suggests, POST requests returning a status code of 201 Created are supposed to contain a Location header which contains the URI of the resource just created.
Thus all you need to do is effectively issuing a GET request to that particular URI. Spring Data REST also has two methods on RepositoryRestConfiguration.setReturnBodyOnCreate(…) and ….setReturnBodyOnUpdate(…) which you can use to configure the framework to immediately return the representation of the resource just created.
Example with Spring Boot:
#Configuration
#EnableMongoRepositories
#Import(RepositoryRestMvcConfiguration.class)
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
RepositoryRestConfiguration restConfiguration = ctx.getBean(RepositoryRestConfiguration.class);
restConfiguration.setReturnBodyOnCreate(true);
}
}
or
#Configuration
#EnableMongoRepositories
#EnableAutoConfiguration
public class Application extends RepositoryRestMvcConfiguration {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
super.configureRepositoryRestConfiguration(config);
config.setReturnBodyOnCreate(true);
}
}
Good Luck!
If you are using Spring Boot, you can add the following lines to your application.properties file for POST (create) and PUT (update) respectively
spring.data.rest.return-body-on-create=true
spring.data.rest.return-body-on-update=true
Here's another variant that uses DI rather than extending RepositoryRestMvcConfiguration or using the ConfigurableApplicationContext.
#SpringBootApplication
#EnableConfigurationProperties
#Configuration
#ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Autowired private RepositoryRestConfiguration repositoryRestConfiguration;
#PostConstruct
public void exposeIds() {
this.repositoryRestConfiguration.setReturnBodyForPutAndPost(true);
}
}

Resources