Spring Boot Rest API Generate QR Code

Tags: zxing generate QR code Rest API QR code Spring Boot QR Code Java QR Code

This Java Spring Boot tutorial to show you how to develop a Spring Boot Restful API which generate QR code image using ZXing library.

Table of contents

  1. Create New Spring Boot Restful API Project
  2. Add ZXing dependencies to the Project
  3. Implement QR Code Service Class
  4. Implement Controller Class
  5. Complete Application Source Code
  6. Run Application
  7. Download The Source Code

Create New Spring Boot Restful API Project

Open IntelliJ IDEA, select the menu File > New > Project. (or click on New Project button at IntelliJ Welcome dialog)

On the New Project dialog, select Spring Initializr and click Next button.

Spring Boot Rest API Generate QR Code

On the Spring initializr Project Settings dialog input the new project information as below and click Next button.

  • Group: dev.simplesolution
  • Artifact: spring-boot-rest-qr-code
  • Type: Gradle
  • Version: 1.0.0
  • Name: spring-boot-rest-qr-code
  • Description: Spring Boot Restful API Generate QR Code
  • Package: dev.simplesolution.restqrcode

Spring Boot Rest API Generate QR Code

On the Dependencies dialog, select below dependencies and click Next button.

  • Spring Web

Spring Boot Rest API Generate QR Code

Select the location for your project and click Finish button to create new Spring Boot project.

Spring Boot Rest API Generate QR Code

Add ZXing dependencies to the Project

To generate the QR code image we use the ZXing library.

To use ZXing library in the Gradle project, add the following dependency to the build.gradle file

implementation group: 'com.google.zxing', name: 'core', version: '3.4.1'

implementation group: 'com.google.zxing', name: 'javase', version: '3.4.1'

If you are using Maven build, add the following dependency to the pom.xml file.

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.1</version>
</dependency>

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.1</version>
</dependency>

Implement QR Code Service Class

At this step we implement a service class to generate QR code image as an array of bytes.

Create a new Java package named dev.simplesolution.restqrcode.service and adding new Java interface named QrCodeService as Java code below.

java/dev/simplesolution/restqrcode/service/QrCodeService.java

package dev.simplesolution.restqrcode.service;

public interface QrCodeService {
    byte[] generateQrCode(String qrCodeContent, int width, int height);
}

Create a new Java package named dev.simplesolution.restqrcode.service.impl, and implement a new Java class named QrCodeServiceImpl as below.

java/dev/simplesolution/restqrcode/service/impl/QrCodeServiceImpl.java

package dev.simplesolution.restqrcode.service.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import dev.simplesolution.restqrcode.service.QrCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
public class QrCodeServiceImpl implements QrCodeService {

    private Logger logger = LoggerFactory.getLogger(QrCodeServiceImpl.class);

    @Override
    public byte[] generateQrCode(String qrCodeContent, int width, int height) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, width, height);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        } catch (WriterException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}

Implement Controller Class

At this step we implement a controller to expose a Restful API to allow download the QR image.

Create a new Java package named dev.simplesolution.restqrcode.controller, and implement a controller class named QrCodeController as following Java code.

java/dev/simplesolution/restqrcode/controller/QrCodeController.java

package dev.simplesolution.restqrcode.controller;

import dev.simplesolution.restqrcode.service.QrCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class QrCodeController {
    private static final int WIDTH = 500;
    private static final int HEIGHT = 500;

    @Autowired
    private QrCodeService qrCodeService;

    @GetMapping("/generate-qr-code")
    public ResponseEntity<byte[]> getQrCode() {
        String contentToGenerateQrCode = "Simple Solution";
        byte[] qrCode = qrCodeService.generateQrCode(contentToGenerateQrCode, WIDTH, HEIGHT);
        return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(qrCode);
    }
}

Complete Application Source Code

At this step we already finished the implementation of the Restful API to generate QR code as following project structure.

Spring Boot Rest API Generate QR Code

Run Application

Execute the Java Spring Boot application, and open the link http://localhost:8080/generate-qr-code on your browser to get the QR code as the following screenshot.

Spring Boot Rest API Generate QR Code

Download The Source Code

The source code in this article can be found at: github.com/simplesolutiondev/spring-boot-rest-qr-code

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-rest-qr-code.git

or download at:

Download Source Code

Happy Coding 😊

Spring Boot Web Generate and Display QR Code as Base64 String

Spring Boot Generate QR Code as Base64 String

Spring Boot Generate QR Code Image Files

Spring Boot Web Upload and Read QR Code Image

Spring Boot Web Generate and Display QR Code

Read QR Code from Image File or Base64 String in Java using ZXing

Generate QR Code in Java using ZXing