Monday, May 22, 2023

How to set base URL for REST in Spring Boot? Example Tutorial

Hello guys, if you are wondering how to set base URL for REST API in Spring Boot then you have come to the right place. Earlier, I have shared best REST API Courses for Java developers, REST API Books,  and a complete guide to create RESTful Web service using Spring Boot, in this article, I will show you how to set a base URL in any spring boot application? If you don't know what is a base URL in a REST application or website, let me give you a brief overview first.  A base URL is the continuous element of your REST API or website's address. For example, you'll notice that the address portion http://twitter.com displays in the address bar whenever you log on to your Twitter account or visit a Twitter profile from your computer. This is the primary or base URL.


How to set base URL for REST in Spring Boot?

Here are the exact steps you can follow to set the base URL for a RESTful web service in Spring Boot:

1. Spring Configuration:

The first step is to create a Spring Boot project, for that you need to with start.spring.io  The main fundamental setup is a bean of type WebMvcRegistrationsAdapter that was presented with Spring Boot 1.4.0. 

This class permits to characterize a custom execution of the RequestMappingHandlerMapping through superseding 'getRequestMappingHanlderMapping'. As expected with Spring Boot we can proclaim such a bean in any class that is explanation with @Configuration.

In this execution we check assuming the proclaiming explanation is commented on with @RestController. It is a decent way to deal with utilize the AnnotationUtils class for this check since it crosses points of interaction, explanations, and super classes.

In this execution we characterize another example that beginnings with 'api' and is trailed by the current patter. Assuming that the @RestController explanation is available.



2. Adding Spring Data REST to a Spring Boot Project

The easiest method for kicking to off is to fabricate a Spring Boot application since Spring Boot has a starter for Spring Data REST and uses auto-design. The accompanying model tells the best way to utilize Gradle to incorporate Spring Data Rest in a Spring Boot project:


Spring Boot configuration with Gradle:

dependencies { 
... 
compile("org.springframework.boot:spring-boot-starter-data-rest") 
... 
}



Spring Boot configuration with Maven
<dependencies> ... <dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-data-rest</artifactId> 
</dependency> ... </dependencies>




3. Get Base URL

While working with web applications utilizing Spring MVC or Spring Boot, in some cases we should get the base URL data of the application to follow through with something. Base URL here is https://google.com. To do this, you can utilize Spring's ServletUriComponentsBuilder class.

Exhaustively, this class has a strategy named fromRequestUri() with an item boundary of HttpServletRequest class. We will get the base URL of the application with the object of this HttpServletRequest class, explicitly as follows:


String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();


The fromRequestUri() strategy will return the pattern (http or https), host, port and setting way of the application. Since our necessities just need mapping, host and port, as may be obvious, we really want to call replacePath() with invalid worth to eliminate this setting way.



4. When to change base URL at runtime?

The demo code above works on things a bit. We ordinarily execute a button in the troubleshoot rendition of the application, where the analyzer can choose the wished server climate. Consequently, contingent upon your circumstance, you most likely need to compose a smidgen more code to choose when and to which base URL Retrofit ought to change to.

Additionally, we just suggest doing this for investigating. We don't think this is a decent approach to making your application work with different servers simultaneously. If your application needs to manage more than one API, search for an alternate variant. The powerful URL instructional exercise may be a decent beginning.

Ultimately, if it's not too much trouble, test in the event that you can essentially switch conditions with your application. For instance, assuming you store client and verification data on the server side, exchanging the climate could create some issues.


Your creation information base in all likelihood doesn't contain similar clients as your advancement data set, right? In our applications, we delete all significant client information and power a new, new login after the analyzer changed the climate through another base URL.


Spring Boot Configurable properties
  • basePath : the root URI for Spring Data REST
  • defaultPageSize : change the default for the quantity of things served in a solitary page
  • maxPageSize : change the most extreme number of things in a solitary page
  • pageParamName : change the name of the query boundary for choosing pages
  • limitParamName : change the name of the query boundary for the quantity of things to show in a page
  • sortParamName : change the name of the query boundary for arranging
  • defaultMediaType : change the default media type to utilize when none is determined
  • returnBodyOnCreate : change whether a body ought to be returned while making another substance
  • returnBodyOnUpdate : change whether a body ought to be returned while refreshing a substance
How to set base URL for REST in Spring Boot?



5. Setting property in application.properties

Spring Boot 1.x:
spring.data.rest.basePath=/api/v1


Spring Boot 2.x:
server.servlet.context-path=/api/v1

The fundamental distinction is way is known as a base way in 1.x and setting way in 2.x, however the importance of both is something very similar.


Both of these change to continuing with "/api/v1".


6. Using Java Property using System

You can utilize the System.setProperty() technique to set the base way.


public static void main(String[] args) { 
    System.setProperty("server.servlet.context-path", "/api/v1"); 
    SpringApplication.run(Application.class, args); 
}


7. Using OS Variables

Mac OS X: Open the terminal and run the command.

$ export SERVER_SERVLET_CONTEXT_PATH=/api/v1



Windows: Run the below command in command prompt.

set SERVER_SERVLET_CONTEXT_PATH=/api/v1


8. Java Command Line Argument

You can set the base way while firing up the spring boot application as underneath.


$ java -jar app.jar --server.servlet.context-path=/api/v1



9. Using RepositoryRestConfigurer

This works spring boot 1.1 before forms and regardless of whether you are not utilizing Spring Boot.

@Configuration class CustomRestMvcConfiguration { 
    @Bean 
    public RepositoryRestConfigurer repositoryRestConfigurer() { 
        return new RepositoryRestConfigurerAdapter() { 
    @Override 
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { 
        config.setBasePath("/api/v1"); 
            } 
        }; 
    } 
}



10. Spring Boot 2.x WebServerFactoryCustomizer

@Bean 
public WebServerFactoryCustomizer webServerFactoryCustomizer() { 
    WebServerFactoryCustomizer customizer = factory -> factory .setContextPath("/api/v1"); 
    logger.info("Setting up the custom base path ");    
    return customizer; 
}



11. Conclusion

That's all about how to set the base URL for RESTful Web Service in Java and Spring Boot application. In this article, we have perceived how to set the setting way in spring boot applications.

The following are the need list from high to low. Continuously Java config will be in higher priority.
  1. Java Config - best
  2. Command Line Args - second
  3. Java System Properties - third
  4. Operating system Level Environment Variables - fourth
  5. application.properties in Current Directory - fifth
  6. application.properties in the classpath (src/main/resources or the packaged jar file) - Least recommended

Other Java and Spring articles you may like
  • 5 courses to learn Spring Boot and Spring Cloud ( courses)
  • 15 Spring Data JPA Interview Questions with answers (questions)
  • 15 Spring Cloud Interview Questions for Java developers (answers)
  • 15 Microservices Interview questions (answers)
  • 5 Courses to learn Spring Cloud and Microservices (courses)
  • 10 Courses to learn Spring Security with OAuth 2 (courses)
  • 5 Course to Master Spring Boot online (courses)
  • 5 Spring Boot Annotations for full-stack Java developers (tutorial)
  • Top 5 Courses to learn Microservices in Java? (courses)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • Top 5 Books and Courses to learn RESTful Web Service (books)
  • 10 Advanced Spring Boot Courses for Java Programmers (courses)
  • 3 ways to change Tomcat port in Spring Boot (tutorial)
  • 10 Spring MVC annotations Java developers should learn (annotations)
  • 3 Best Practices Java Programmers can learn from Spring (best practices)

Thanks for reading this article so far; if you find Java Spring Boot, and REST tutorial useful, please share them with your friends and colleagues.

P. S. - If you are new to Spring Boot and want to learn about Spring Boot and look for a free Spring Boot online course, I also recommend you join the Introducing Spring Boot (FREE ) class by Dan Vega on Udemy. It's one of the best free courses to learn Spring Boot for Java developers. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.