Spring Boot Azure Computer Vision API: Complete End-to-End Integration Guide


Flow Explanation:

  1. User → Spring Boot API: Sends an image URL via an HTTP GET request (/api/vision/analyze).
  2. Spring Boot API → Azure Computer Vision: Calls Azure’s API via an HTTP POST request with the image URL.
  3. Azure Computer Vision → Spring Boot API: Returns the analysis results (JSON response with objects, tags, descriptions).
  4. Spring Boot API → User: Sends the processed data back to the user.

This showcases an end-to-end integration of Spring Boot with Azure Computer Vision API for image recognition.


Here's a complete end-to-end guide for integrating Azure Computer Vision with Spring Boot. This guide covers:

✅ Setting up Azure Computer Vision API
✅ Creating a Spring Boot project
✅ Implementing REST API to process images
✅ Sending requests & handling responses


Step 1: Set Up Azure Computer Vision API

  1. Create an Azure Computer Vision resource
    • Go to Azure Portal
    • Search for "Computer Vision" and create a new resource
    • Choose a pricing tier (Free or Paid)
    • Copy the Subscription Key and Endpoint

Step 2: Create a Spring Boot Project

Generate a Spring Boot project using Spring Initializr with:

  • Spring Web (for REST API)
  • Lombok (optional)

Maven Dependencies (pom.xml)

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Starter JSON -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

    <!-- Lombok (optional) -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- Apache HttpClient (for making HTTP calls) -->
    <dependency>
        <groupId>org.apache.httpcomponents.client5</groupId>
        <artifactId>httpclient5</artifactId>
    </dependency>
</dependencies>

Step 3: Create Configuration Properties

Store Azure API Key and Endpoint in application.properties:

azure.computervision.endpoint=https://your-endpoint.cognitiveservices.azure.com/
azure.computervision.key=your-azure-key

Step 4: Create a Service to Call Azure API

Create AzureVisionService.java to send images to Azure Computer Vision API.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
@RequiredArgsConstructor
public class AzureVisionService {

    @Value("${azure.computervision.endpoint}")
    private String endpoint;

    @Value("${azure.computervision.key}")
    private String apiKey;

    private final ObjectMapper objectMapper;

    public String analyzeImage(String imageUrl) throws IOException {
        String url = endpoint + "/vision/v3.2/analyze?visualFeatures=Description,Tags,Objects";
        
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost request = new HttpPost(url);
            request.setHeader("Ocp-Apim-Subscription-Key", apiKey);
            request.setHeader("Content-Type", "application/json");

            // Request body
            String jsonBody = "{\"url\":\"" + imageUrl + "\"}";
            request.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));

            // Execute request
            try (CloseableHttpResponse response = client.execute(request)) {
                return objectMapper.readTree(response.getEntity().getContent()).toPrettyString();
            }
        }
    }
}

Step 5: Create a REST Controller

Create AzureVisionController.java to expose an API endpoint.

import com.example.azurevision.service.AzureVisionService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/api/vision")
@RequiredArgsConstructor
public class AzureVisionController {

    private final AzureVisionService azureVisionService;

    @GetMapping("/analyze")
    public String analyzeImage(@RequestParam String imageUrl) throws IOException {
        return azureVisionService.analyzeImage(imageUrl);
    }
}

Step 6: Test the API

Run the Spring Boot application and send a GET request:

curl "http://localhost:8080/api/vision/analyze?imageUrl=https://example.com/sample-image.jpg"

Response (Sample Output)

{
  "description": {
    "tags": ["outdoor", "tree", "sky"],
    "captions": [
      {
        "text": "A beautiful landscape with trees",
        "confidence": 0.98
      }
    ]
  },
  "tags": [
    { "name": "tree", "confidence": 0.99 },
    { "name": "sky", "confidence": 0.97 }
  ],
  "objects": [
    { "object": "car", "confidence": 0.95, "rectangle": { "x": 100, "y": 50, "w": 200, "h": 150 } }
  ]
}

Summary

✔️ Set up Azure Computer Vision API
✔️ Created Spring Boot project
✔️ Built REST API to analyze images
✔️ Sent image URLs & processed responses

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example