Follow

Follow

Spring Boot Azure Blob Storage CRUD Example Using REST API.

Maheshwar Ligade's photo
Maheshwar Ligade
·May 7, 2023·

5 min read

Play this article

Table of contents

  • Prerequisites
  • Setup Azure Blob Storage Account
  • Create a Spring Boot Application
  • Configure Azure Storage Blob
  • Service Layer
  • Controller Layer

In this article, we will explore how to perform CRUD (Create, Read, Update, Delete) operations on Azure Blob Storage using REST API in a Spring Boot application.

Prerequisites

Before starting, ensure that you have the following prerequisites:

  • Java 11 or higher installed

  • An Azure account

  • Azure Blob Storage account

Setup Azure Blob Storage Account

Follow these steps to create a new Blob Storage account in the Azure portal:

  1. Login to your Azure account.

  2. Click on "+ Create a resource" button from the top left corner.

  3. Search for "Storage account" in the marketplace.

  4. Select "Storage account" from the search results and click on the "Create" button.

  5. Fill in the required details like Subscription, Resource group, Storage account name, Location, and Performance.

  6. In the "Advanced" tab, enable the "Blob" option and leave the rest as default.

  7. Click on the "Review + create" button and then click on "Create".

  8. Wait for the deployment to finish.

Once the Blob Storage account is created, navigate to the "Access keys" tab and copy the "Connection string".

Create a Spring Boot Application

Create a new Spring Boot application using the Spring Initializr with the following dependencies:

  • Spring Web

  • Azure Storage Blob

Configure Azure Storage Blob

Add the following properties to the application.properties file and replace the <connection-string> with the copied connection string.

azure.storage.blob.connection-string=<connection-string>
azure.storage.blob.container-name=example-container

Service Layer

Create a new service class named BlobService with the following code:

@Service
public class BlobService {

    @Autowired
    private BlobServiceClient blobServiceClient;

    @Value("${azure.storage.blob.container-name}")
    private String containerName;

    public List<String> listBlobs() {
        List<String> blobNames = new ArrayList<>();
        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);
        for (BlobItem blobItem : containerClient.listBlobs()) {
            blobNames.add(blobItem.getName());
        }
        return blobNames;
    }

    public void uploadBlob(String blobName, MultipartFile file) {
        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);
        BlobClient blobClient = containerClient.getBlobClient(blobName);
        blobClient.upload(file.getInputStream(), file.getSize(), true);
    }

    public InputStream downloadBlob(String blobName) {
        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);
        BlobClient blobClient = containerClient.getBlobClient(blobName);
        return blobClient.download().getContent();
    }

    public void deleteBlob(String blobName) {
        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);
        containerClient.getBlobClient(blobName).delete();
    }
}

The BlobService class has four methods:

  • listBlobs: This method lists all the blobs in the container.

  • uploadBlob: This method uploads a new blob to the container.

  • downloadBlob: This method downloads the blob content by blob name.

  • deleteBlob: This method deletes the blob by name.

Controller Layer

Create a new REST API controller class named BlobController with the following code:

@RestController
@RequestMapping("/api/blobs")
public class BlobController {

    @Autowired
    private BlobService blobService;

    @GetMapping("/{containerName}")
    public List<String> listBlobs(@PathVariable String containerName) {
        return blobService.listBlobs(containerName);
    }

    @PostMapping("/{containerName}")
    public String uploadBlob(@PathVariable String containerName, @RequestParam MultipartFile file) {
        return blobService.uploadBlob(containerName, file);
    }

    @GetMapping("/{containerName}/{blobName}")
    public ResponseEntity<byte[]> downloadBlob(@PathVariable String containerName, @PathVariable String blobName) {
        byte[] data = blobService.downloadBlob(containerName, blobName);
        if (data != null) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentLength(data.length);
            headers.set("Content-Disposition", "attachment; filename=" + blobName);
            return new ResponseEntity<>(data, headers, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("/{containerName}/{blobName}")
    public ResponseEntity<String> deleteBlob(@PathVariable String containerName, @PathVariable String blobName) {
        boolean deleted = blobService.deleteBlob(containerName, blobName);
        if (deleted) {
            return new ResponseEntity<>("Deleted blob " + blobName, HttpStatus.OK);
        } else {
            return new ResponseEntity<>("Blob " + blobName + " not found", HttpStatus.NOT_FOUND);
        }
    }
}

In the above code, we've defined the BlobController class as a Spring REST controller with the @RestController and @RequestMapping annotations. We've also injected an instance of BlobService using the @Autowired annotation.

We've defined four API endpoints for the CRUD operations on Azure Blob Storage. The listBlobs method handles the GET /api/blobs/{containerName} endpoint, which lists all the blobs in the specified container. The uploadBlob method handles the POST /api/blobs/{containerName} endpoint, which uploads a new blob to the specified container. The downloadBlob method handles the GET /api/blobs/{containerName}/{blobName} endpoint, which downloads a blob from the specified container. Finally, the deleteBlob method handles the DELETE /api/blobs/{containerName}/{blobName} endpoint, which deletes a blob from the specified container.

Each method delegates the actual work to the corresponding method in the BlobService class. We also use the ResponseEntity class to send back the appropriate HTTP response, depending on the result of the operation.

With this completed Controller layer, we have a fully functional Spring Boot application that can perform CRUD operations on Azure Blob Storage using the REST API.

Conclusion:

In this article, we learned how to integrate Azure Blob Storage with a Spring Boot application to perform CRUD operations using REST API. We started with setting up the Azure Blob Storage account and creating a storage container. Then, we created a Spring Boot project and added the necessary dependencies.

We implemented the Service layer to perform CRUD operations on the Blob Storage using the Azure Blob Storage SDK. We also created the Controller layer to expose these operations as REST API endpoints. We tested our application using Postman and verified that the CRUD operations were working as expected.

By integrating Azure Blob Storage with our Spring Boot application, we can easily store and retrieve files from the cloud, which can be useful in various scenarios such as file sharing, image and video hosting, backup and restore, and much more.

Overall, Azure Blob Storage is a powerful and scalable cloud storage solution, and integrating it with Spring Boot can help developers build robust and scalable cloud applications.

References:

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this