# Spring Boot Integration with Google Bard - Web API to access the Google AI chat box
I have created a Java library (opens new window) for Google Bard
that can help us make a simple call to ask questions and get answers. Now I integrated the Java library into the Spring Boot application. So that we can make it publicly available to others.
# Add Dependencies
Add the pkslow google-bard
to the Spring Boot
project:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.pkslow</groupId>
<artifactId>google-bard</artifactId>
<version>0.1.0</version>
</dependency>
</dependencies>
# Create a bean of GoogleBardClient
We need to create a bean of GoogleBardClient
before you can use it to ask the questions:
@Configuration
public class GoogleBardConfig {
@Bean
public GoogleBardClient googleBardClient(@Value("${ai.google-bard.token}") String token) {
return new GoogleBardClient(token);
}
}
# BardController
Inject the GoogleBardClient
bean in the Controller, and get the question from request param.
@RestController
@RequestMapping("/google-bard")
public class BardController {
private final GoogleBardClient client;
public BardController(GoogleBardClient client) {
this.client = client;
}
@GetMapping("/ask")
public BardAnswer ask(@RequestParam("q") String question) {
Answer answer = client.ask(question);
if (answer.status() == AnswerStatus.OK) {
return new BardAnswer(answer.chosenAnswer(), answer.draftAnswers());
}
if (answer.status() == AnswerStatus.NO_ANSWER) {
return new BardAnswer("No Answer", null);
}
throw new RuntimeException("Can't access to Google Bard");
}
}
After we asked and got the answers, we will return the related DTO object.
# properties
Set the token from browser:
server.port=8088
ai.google-bard.token=UgiXYPjpaIYuE9K_3BSqCWnT2W**********************
# How to get the token?
Go to https://bard.google.com/
- F12 for console
- Copy the values
- Session: Go to Application → Cookies →
__Secure-1PSID
. Copy the value of that cookie.
- Session: Go to Application → Cookies →
# Test with Postman
Question 1: How to be a good father?
Queston 2: what is pkslow.com?
Log:
# Code
The code is on GitHub (opens new window).
References: