Photo Retrieval Endpoint

Now that we can upload photos, we need to implement the endpoint that allows users to retrieve them.

This is particularly important as we want to display restaurant photos to users before they log in, making using the site more engaging.

Implementing the Photo Retrieval Endpoint

The photo retrieval endpoint needs to return the actual photo file along with the correct content type, so browsers can display it properly.

Let's add the retrieval endpoint to our existing PhotoController:

@GetMapping("/{id:.+}") public ResponseEntity<Resource> getPhoto(@PathVariable String id) { return photoService.getPhotoAsResource(id).map(photo -> ResponseEntity.ok() .contentType(MediaTypeFactory .getMediaType(photo) .orElse(MediaType.APPLICATION_OCTET_STREAM)) .header(HttpHeaders.CONTENT_DISPOSITION, "inline") .body(photo) ).orElse(ResponseEntity.notFound().build()); }

Let's break down the key components of this endpoint:

  • The {id:.+} path variable pattern allows for file extensions in the ID
  • We use ResponseEntity to control the HTTP response details
  • MediaTypeFactory helps determine the correct content type for the photo
  • The Content-Disposition: inline header tells browsers to display the image rather than download it

Updating Security Configuration

To allow unauthenticated access to photos, we need to update our security configuration:

@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth // Allow for loading of photos .requestMatchers(HttpMethod.GET, "/api/photos/**").permitAll() .anyRequest().authenticated() ) // ... rest of the security configuration return http.build(); }

This configuration specifically allows GET requests to /api/photos/** without authentication, while maintaining security for other endpoints.

Testing the Endpoint

You can test the endpoint by:

  1. First uploading a photo and noting the returned ID
  2. Then accessing the photo directly in your browser using the path /api/photos/{id}

For example, if your photo ID is 123e4567-e89b-12d3-a456-426614174000.jpg, you would access it at: http://localhost:8080/api/photos/123e4567-e89b-12d3-a456-426614174000.jpg

Summary

  • Implemented GET endpoint at /api/photos/{id} to retrieve photos
  • Used ResponseEntity to control response headers and content type
  • Updated security config to allow public access to photo retrieval
  • Photos are served with inline disposition for browser display
© 2026 Devtiro Ltd. All rights reserved