With the capability of training and building custom models, Firebase is an effective mobile app development toolkit to deploy machine learning in mobile devices. In this article, we will use the Cloud Firestore and we will learn how to connect to Firebase Firestore Database and build a CRUD application using Firebase with Spring boot Rest API.
We, at Oodles, as a high-performance Machine Learning Development Company, explore how businesses can use the Firebase database to build custom applications.
Firebase is a cloud-based document store that is suitable for developing real-time applications. Firebase is owned by Google and is only available on GCP (Google Cloud Platform). The Firebase Realtime Database is a cloud-hosted database. Cloud Firestore is a scalable, flexible DB for web, server, mobile development from Firebase, and Google Cloud Platform. Data is stored in firebase as JSON form and synchronized in realtime to every connected client. Firebase is popular with developers for its rich and complete set of features to create applications without backends and servers. Following Cloud Firestore's NoSQL data model, you store data in documents that contain fields mapping to values. One collection can contain many documents and there are many fields, types, and values contained in a single document. Documents support many different data types like simple strings, number, timestamps, array, map, geopoint, complex and nested objects.
Firebase from Google offers two cloud-based-accessible database solutions that support realtime data syncing:
Cloud Firestore is a flexible database for mobile and web apps. Cloud Firestore is richer, faster, and more scalable than the Realtime Database.
Realtime Database is the Firebase's first and original database. Mobile apps requiring synced states across clients in realtime, in this case, it is an efficient and low-latency solution.
1. Go to https://console.firebase.google.com and sign up for an account.
2. Click the Add Project button
3. Type database name in the field.
4. Click the Create project button and click continue.
5. Now we have created a project on Firebase.
6. Then go to the cloud Firestore and click data.
7. Now you have to create a collection in which you can store documents.
8. In the collection, you can add JSON documents, delete documents, and delete fields also.
9. Once created the collection, we will go to project settings -> service Accounts tab to generate the key, download, and save it in your spring boot project, that we will use to connect to the firebase Firestore database.
10. Then go to https://start.spring.io/ and create a maven project, Once the project created then open the pom.xml file and add the below dependency.
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.11.0</version>
</dependency>
11. Add a service class named FirebaseInitialize which we will use to make a connection to firebase during the application startup. The class looks like this.
@Service
public class FBInitialize {
@PostConstruct
public void initialize() {
try {
FileInputStream serviceAccount =
new FileInputStream("./serviceaccount.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://chatapp-e6e15.firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
e.printStackTrace();
}}}
@Service and @PostConstruct these are the two annotations from Spring Boot.
The first line reads the serviceAccount.json which we generated on the firebase project settings.
It connects to firebase with FirebaseApp.initializeApp using the firebaseoptions builder class in which will have credentials that we extracted from serviceAccount.json and the database URL.
Now firebase connection is initialized, so let's perform crud operations.
public class Patient {
private String name;
private int age;
private String city;
# setters and getters
}
@Service
public class PatientService {
public static final String COL_NAME="users";
public String savePatientDetails(Patient patient) throws InterruptedException, ExecutionException {
Firestore dbFirestore = FirestoreClient.getFirestore();
ApiFuture<WriteResult> collectionsApiFuture = dbFirestore.collection(COL_NAME).document(patient.getName()).set(patient);
return collectionsApiFuture.get().getUpdateTime().toString();
}
public Patient getPatientDetails(String name) throws InterruptedException, ExecutionException {
Firestore dbFirestore = FirestoreClient.getFirestore();
DocumentReference documentReference = dbFirestore.collection(COL_NAME).document(name);
ApiFuture<DocumentSnapshot> future = documentReference.get();
DocumentSnapshot document = future.get();
Patient patient = null;
if(document.exists()) {
patient = document.toObject(Patient.class);
return patient;
}else {
return null;
}
}
public String updatePatientDetails(Patient person) throws InterruptedException, ExecutionException {
Firestore dbFirestore = FirestoreClient.getFirestore();
ApiFuture<WriteResult> collectionsApiFuture = dbFirestore.collection(COL_NAME).document(person.getName()).set(person);
return collectionsApiFuture.get().getUpdateTime().toString();
}
public String deletePatient(String name) {
Firestore dbFirestore = FirestoreClient.getFirestore();
ApiFuture<WriteResult> writeResult = dbFirestore.collection(COL_NAME).document(name).delete();
return "Document with Patient ID "+name+" has been deleted";
}}
@RestController
public class PatientController {
@Autowired
PatientService patientService;
@GetMapping("/getPatientDetails")
public Patient getPatient(@RequestParam String name ) throws InterruptedException, ExecutionException{
return patientService.getPatientDetails(name);
}
@PostMapping("/createPatient")
public String createPatient(@RequestBody Patient patient ) throws InterruptedException, ExecutionException {
return patientService.savePatientDetails(patient);
}
@PutMapping("/updatePatient")
public String updatePatient(@RequestBody Patient patient ) throws InterruptedException, ExecutionException {
return patientService.updatePatientDetails(patient);
}
@DeleteMapping("/deletePatient")
public String deletePatient(@RequestParam String name){
return patientService.deletePatient(name);
}
}
The Oodles AI team has hands-on experience with advanced tools like Firebase, TensorFlow, Tesseract OCR, and more to build enterprise-grade AI solutions.
Connect with our AI development team to know more about our artificial intelligence services.