Fetch Firestore Documents with REST

Joshua Bence
Sep 4, 2018 · 3 min read

Google offers a beta Firestore API that can be accessed over HTTP. This allows developers to use external content without having to include the Firebase library. This opens up the possibilities for developers to use Firebase in more unique ways while still following standard web practices.

How to construct the API URL and request data with fetch

const projectID = 'PROJECT_ID'
const key = 'API_KEY'
const doc = 'DOCUMENT'
const url = `https://firestore.googleapis.com/v1beta1/projects/${projectID}/databases/(default)/documents/${doc}?key=${key}`
// Use fetch to request the API information
fetch(url)
.then(response => response.json())
.then(json => console.log(json));

Setup a Firestore database

Login to Firebase, create a new project and create a new Firestore database. Make sure database rules at least allow read. The project ID and API Key are found on the Project settings page.

service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read;
}
}
}

Add FireStore Data to Fetch

In this example, add a players collection and add 1 document. On that document add some fields you want to return.

Collection named players with 1 document with 3 fields

The document path is the collection ID and document ID. If you add more nested collections, this pattern remains the same.

const doc = 'players/8SB90IpAbzCmIH7N5tkG'

Fetch request returns data in this format

Conflict! The fields all have data types as keys for the value

When working with fields, you have to know the data type before you can get the value. The problem gets more complex when fields are nested within fields using Arrays or other Objects.

What if we can get the values without having to know data type?

After working with the API on projects, I created a JS function to do just that.

Import the FireStoreParser and parse the response JSON

// const FireStoreParser = require('firestore-parser')
import FireStoreParser from 'firestore-parser'
const projectID = 'PROJECT_ID'
const key = 'API_KEY'
const doc = 'DOCUMENT'
const url = `https://firestore.googleapis.com/v1beta1/projects/${projectID}/databases/(default)/documents/${doc}?key=${key}`
// Use fetch to request the API information
fetch(url)
.then(response => response.json())
.then(json => FireStoreParser(json))
.then(json => console.log(json))

Fields are now in a more usable format!

The parser works with all the current data types. If you see any problems, open an issue on Github. PRs are always welcome!

la fin

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade