Restaurant Search Controller
Now that we have our service layer and DTOs ready, we can create the REST API endpoint that will power our restaurant search functionality.
Our goal is to make this endpoint accessible to everyone, whether they're logged in or not.
Adding the Search Endpoint
Let's add a new search method to our existing RestaurantController class. This method will handle incoming search requests and return restaurant results to the caller.
@RestController
@RequestMapping(path = "/api/restaurants")
@RequiredArgsConstructor
public class RestaurantController {
// ...
@GetMapping
public Page<RestaurantSummaryDto> searchRestaurants(
@RequestParam(required = false) String q,
@RequestParam(required = false) Float minRating,
@RequestParam(required = false) Float latitude,
@RequestParam(required = false) Float longitude,
@RequestParam(required = false) Float radius,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "20") int size) {
Page<Restaurant> searchResult = restaurantService.searchRestaurants(
q,
minRating,
latitude,
longitude,
radius,
PageRequest.of(page - 1, size)
);
return searchResult.map(restaurantMapper::toSummaryDto);
}
}Configuring Public Access
To allow non-authenticated users to access our search endpoint, we need to update our security configuration. We'll modify the SecurityConfig class to permit public access to our restaurant endpoints.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth ->
auth
.requestMatchers(HttpMethod.GET, "/api/photos/**").permitAll()
// Allow public access to restaurant search
.requestMatchers("/api/restaurants/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 ->
oauth2.jwt(jwt ->
jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())
))
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.csrf(csrf -> csrf.disable());
return http.build();
}
}Getting Lat/Lon
You can use the following URL in Kibana's dev console to return all records:
GET _search
{
"query": {
"match_all": {} // match_all
}
}You can then use the lat/lons for testing geospatial search.
Summary
- Implemented the
searchRestaurantsendpoint inRestaurantController - Added support for multiple search parameters using
@RequestParam - Updated
SecurityConfigto allow public access to/api/restaurants/**