DEV Community

harrissolangi
harrissolangi

Posted on

Creating a basic GET API with Firebase Cloud Functions and Firestore

Creating a GET API that fetches 100 records using Firebase Cloud Functions and Firestore is relatively simple. Here's an example of how to do it:

  1. Start by creating a new Firebase Cloud Function and selecting an HTTP trigger.

  2. In the function's index.js file, import the Firebase and Firestore modules by adding the following lines at the top:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

  1. Then in the function's body you can use the get() method from the firestore collection object with the limit() method that sets the maximum number of documents to retrieve, in this case, you want to get 100 documents.

exports.get100Records = functions.https.onRequest((req, res) => {
db.collection("collection_name")
.limit(100)
.get()
.then(snapshot => {
const data = [];
snapshot.forEach(doc => {
data.push(doc.data());
});
res.json(data);
})
.catch(error => {
res.status(500).send(error);
});
});

  1. Once your function is ready, you will want to deploy it to Firebase. This can be done by running the following command in your command line: firebase deploy --only functions

  2. Now you can test the API endpoint by sending a GET request to the endpoint and checking the results.

Note that this is a simplified example.

Another slightly complex example is shared below :

`const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.get100Records = functions.https.onRequest((req, res) => {
// Get request parameters
const { orderBy, orderDirection, filterBy } = req.query;

// Create a reference to the Firestore collection
let collectionRef = db.collection('collection_name');

// Apply sorting if specified
if (orderBy && orderDirection) {
    collectionRef = collectionRef.orderBy(orderBy, orderDirection);
}

// Apply filtering if specified
if (filterBy) {
    collectionRef = collectionRef.where(filterBy.field, filterBy.op, filterBy.value);
}

// Get the first 100 documents
collectionRef.limit(100).get()
.then(snapshot => {
    const data = [];
    snapshot.forEach(doc => {
        data.push(doc.data());
    });
    res.json(data);
})
.catch(error => {
    console.log(error);
    res.status(500).send(error);
});
Enter fullscreen mode Exit fullscreen mode

});
`

In this example, the API endpoint accepts query parameters for sorting (orderBy and orderDirection) and filtering (filterBy) the data before fetching the first 100 records.

You can test this endpoint by sending a GET request to the endpoint with the appropriate query parameters.

Top comments (0)