spring boot
rest api
base url
configuration
java

How to set base url for rest in spring boot?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

In modern web development, REST (Representational State Transfer) APIs have become a standard for building scalable and maintainable server-side applications. Spring Boot, with its vast ecosystem, provides robust support for developing RESTful services. One common task in these applications is setting a base URL for all REST endpoints. This is crucial for the organization of URL patterns, versioning APIs, and improving the maintainability of the code.

This article provides a detailed explanation of how to set a base URL in a Spring Boot application and explores related concepts with practical examples.

Understanding Spring Boot Controller

Before diving into setting a base URL, it's essential to understand the role of a Controller in Spring Boot. A Controller in Spring Boot is annotated with @RestController to handle HTTP requests in a RESTful manner. The annotations @RequestMapping, @GetMapping, @PostMapping, etc., are used to map requests to the controller methods.

java
1@RestController
2@RequestMapping("/api")
3public class MyController {
4
5    @GetMapping("/hello")
6    public String sayHello() {
7        return "Hello, World!";
8    }
9}

In the snippet above, the MyController class is handling HTTP GET requests on the "/api/hello" endpoint.

Setting the Base URL

A base URL is a prefix added to all the URLs for a set of REST endpoints. It is useful in scenarios where you want to change the entire prefix at once, potentially for versioning or organizational purposes.

Using the @RequestMapping Annotation

The primary way to set a base URL in Spring Boot is through the @RequestMapping annotation at the class level. This consolidates the URL patterns for all methods within the controller.

Here's how you can define a base URL using @RequestMapping:

java
1@RestController
2@RequestMapping("/api/v1")
3public class MyController {
4
5    @GetMapping("/users")
6    public List<String> getUsers() {
7        return List.of("Alice", "Bob", "Charlie");
8    }
9
10    @PostMapping("/users")
11    public String addUser(@RequestBody String name) {
12        // Add user logic here
13        return "User added: " + name;
14    }
15}

In this example, the base URL /api/v1 is set, so any method in MyController will handle requests prefixed with /api/v1.

Global Base URL with Configuration

Sometimes you may want to configure a global base URL that applies application-wide. This can be achieved through properties files and configuration classes.

First, define your base URL in the application.properties or application.yml file:

properties
application.base-url=/api/v1

Then, use this property in your application's configuration:

java
1@Configuration
2public class WebConfig implements WebMvcConfigurer {
3
4    @Value("${application.base-url}")
5    private String baseUrl;
6
7    @Override
8    public void addInterceptors(InterceptorRegistry registry) {
9        registry.addInterceptor(new BaseUrlInterceptor(baseUrl));
10    }
11}
12
13public class BaseUrlInterceptor implements HandlerInterceptor {
14    private final String baseUrl;
15
16    public BaseUrlInterceptor(String baseUrl) {
17        this.baseUrl = baseUrl;
18    }
19
20    @Override
21    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
22        // Modify the request URI to include the base URL
23        String fullPath = baseUrl + request.getRequestURI();
24        try {
25            request.getRequestDispatcher(fullPath).forward(request, response);
26        } catch (Exception ex) {
27            // Handle exceptions
28        }
29        return true;
30    }
31}

This custom BaseUrlInterceptor adds the functionality to prepend a base URL to every request. It uses the value from the properties file, allowing centralized management of the base URL.

Summary of Key Points

FeatureDescriptionExample Usage
@RequestMappingSets a base URL at the controller level.@RequestMapping("/api/v1")
Global Base URLApplies a base URL across the applicationDefined in application.properties
Custom InterceptorHandles base URL in a pre-processing manner using interceptor.BaseUrlInterceptor implementation

Additional Considerations

API Versioning

In any robust REST API design, versioning is crucial. By setting the base URL with a version component (e.g., /api/v1), you facilitate seamless transitioning between different API versions. Future versions can be introduced as /api/v2, thus making the endpoints backward-compatible.

Dynamic Base URL

In some cases, it may be necessary to construct dynamic base URLs, such as those generated based on conditions or configurations fetched at runtime. In such scenarios, you might integrate with a settings microservice or feature flags that dictate the current URL scheme.

Consistency and Maintenance

Ensuring a consistent base URL structure across microservices or modules makes it easier for consumers (other services or client apps) to predict endpoint patterns and adapt as necessary. Utilizing properties files also helps in maintaining clean and readable code.

Conclusion

Setting a base URL in a Spring Boot RESTful service is straightforward yet highly valuable for the organization, scalability, and versioning of APIs. By following the practices outlined in this guide, developers can efficiently manage their application endpoint structures, enhance maintainability, and simplify future transitions to new versions or configurations.

Through careful planning and utilization of Spring Boot's rich feature set, creating well-structured, maintainable, and scalable RESTful services is both a manageable and rewarding task.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.